LINQ以多种条件加入C#

时间:2010-06-11 05:44:16

标签: c# linq join multiple-conditions

我在C#中有多个条件的LINQ Joining语句。

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

加入无效。我做错了什么?

3 个答案:

答案 0 :(得分:95)

AFAIK你只能这样加入:

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
    }

主要要求是: 您加入的匿名对象中的属性名称,类型和顺序必须匹配。

您不能在联接中使用ANDs OR等。只是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};
}

寻址名称和属性顺序很简单,寻址类型可以通过转换/转换/解析/调用方法等来实现。这可能并不总是适用于LINQ to EF或SQL或NHibernate,大多数方法调用肯定不起作用,在运行时会失败,所以YMMV。 这是因为它们被复制到匿名对象中的公共只读属性,因此只要表达式生成正确类型的值连接属性 - 您应该没问题。

答案 1 :(得分:5)

您的and应该是&&条款中的where

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

应该是

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

答案 2 :(得分:0)

如果您不需要相等的对象条件,请使用交叉连接序列:

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