LINQ Connection in C # with multiple conditions

I have a LINQ Joining statement in C # with several conditions.

var possibleSegments = from epl in eventPotentialLegs join sd in segmentDurations on new { epl.ITARequestID, epl.ITASliceNumber, epl.DepartAirportAfter, epl.AirportId_Origin, epl.AirportId_Destination } equals new { sd.ITARequestId, sd.SliceIndex, sd.OriginAirport, sd.DestinationAirport } where epl.DepartAirportAfter > sd.UTCDepartureTime and epl.ArriveAirportBy > sd.UTCArrivalTime select new PossibleSegments{ ArrivalTime = sd.arrivalTime }; 

The connection is not working properly. What am I doing wrong?

+44
c # join linq multiple-conditions
Jun 11 '10 at 5:44
source share
3 answers

AFAIK you can join only this way:

 var query = from obj_i in set1 join obj_j in set2 on new { JoinProperty1 = obj_i.SomeField1, JoinProperty2 = obj_i.SomeField2, JoinProperty3 = obj_i.SomeField3, JoinProperty4 = obj_i.SomeField4 } equals new { JoinProperty1 = obj_j.SomeOtherField1, JoinProperty2 = obj_j.SomeOtherField2, JoinProperty3 = obj_j.SomeOtherField3, JoinProperty4 = obj_j.SomeOtherField4 } 

Basic requirements: Property names, types, and order in the anonymous objects you connect to must match.

You cannot use ANDs OR etc. in connections. Just object1 is equal to object2.

More advanced stuff in this LinqPad example:

 class c1 { public int someIntField; public string someStringField; } class c2 { public Int64 someInt64Property {get;set;} private object someField; public string someStringFunction(){return someField.ToString();} } void Main() { var set1 = new List<c1>(); var set2 = new List<c2>(); var query = from obj_i in set1 join obj_j in set2 on new { JoinProperty1 = (Int64) obj_i.someIntField, JoinProperty2 = obj_i.someStringField } equals new { JoinProperty1 = obj_j.someInt64Property, JoinProperty2 = obj_j.someStringFunction() } select new {obj1 = obj_i, obj2 = obj_j}; } 

Name addressing and property ordering is simple, addressing types can be achieved using casting / transforming / parsing / calling methods, etc. This may not always work with LINQ to EF or SQL or NHibernate, most method calls will definitely not work and will not work at runtime, so YMMV. This is because they are copied to read-only public properties in anonymous objects, so as long as your expression creates the correct type, the join property - you should be fine.

+79
Oct 18 '11 at 19:56
source share

Your and should be && in the where clause.

 where epl.DepartAirportAfter > sd.UTCDepartureTime and epl.ArriveAirportBy > sd.UTCArrivalTime 

it should be

 where epl.DepartAirportAfter > sd.UTCDepartureTime && epl.ArriveAirportBy > sd.UTCArrivalTime 
+5
Jun 11 2018-10-10 at
source share

If you do not need an equal condition for the object, use cross-sequences:

 var query = from obj1 in set1 from obj2 in set2 where obj1.key1 == obj2.key2 && obj1.key3.contains(obj2.key5) [...conditions...] 
0
Apr 18 '17 at 6:46
source share



All Articles