LINQ在C#中join多个条件

我在C#中有一个LINQ Join语句,有多个条件。

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 }; 

join无法正常工作。 我究竟做错了什么?

AFAIK你只能这样join:

 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 } 

主要的要求是:你join的匿名对象中的属性名称,types和顺序必须匹配。

你不能在连接中使用ANDs等。 只是object1等于object2。

在这个LinqPad例子中更高级的东西:

 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}; } 

寻址名称和属性顺序很简单,寻址types可以通过铸造/转换/parsing/调用方法等来实现。这可能不总是与LINQ到EF或SQL或NHibernate的工作,大多数方法调用绝对不会工作,并会失败运行时间,所以YMMV。 这是因为它们被复制到匿名对象中的公共只读属性,所以只要您的expression式生成正确types的值的连接属性 – 你应该没问题。

您应该在where子句中使用&&

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

应该

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

如果你不需要等同的对象条件使用交叉连接序列:

 var query = from obj1 in set1 from obj2 in set2 where obj1.key1 == obj2.key2 && obj1.key3.contains(obj2.key5) [...conditions...] 
Interesting Posts