如何基于属性获得两个类的交集

时间:2016-04-25 19:44:07

标签: c# linq aggregate intersection

我有这个班级

public class FlightSegment{
     public string ClassName { get;set;}
}

我希望通过FlightSegments

获得ClassName
void Main()
{
    var list1 = new List<FlightSegment>() { 
        new FlightSegment{ ClassName = "A"},
        new FlightSegment { ClassName = "B"}
    };      
    var list2 = new List<FlightSegment>() { 
        new FlightSegment{ ClassName = "B"},
        new FlightSegment { ClassName = "C"}
    }; 

    var listOfLists = new List<List<FlightSegment>>() { list1, list2 };     
    var intersection = listOfLists.Aggregate((previousList, nextList) => previousList.Intersect(nextList).ToList());        
    Console.WriteLine(intersection); //Gives me empty result

}

我试过这样的事情:

    var intersection = listOfLists.Aggregate((previousList, nextList) =>   
      previousList.Select(e=>e.ClassName).Intersect(nextList.Select(e=>e.ClassName)).ToList());

但是给出错误:

Cannot convert expression type System.Collection.Generic.List<string> to return type System.Collection.Generic.List<FlightSegment>

1 个答案:

答案 0 :(得分:5)

您可以使用Intersect方法传递IEqualityComparer根据ClassName属性进行比较:

class FlightComparer : EqualityComparer<FlightSegment>
{
    public override bool Equals(FlightSegment x, FlightSegment y)
    {
        return x.ClassName == y.ClassName;
    }

    public override int GetHashCode(FlightSegment obj)
    {
        return obj.ClassName.GetHashCode();
    }
}

然后,使用此比较器进行交叉:

var list1 = new List<FlightSegment>() { 
    new FlightSegment{ ClassName = "A"},
    new FlightSegment { ClassName = "B"}
};      
var list2 = new List<FlightSegment>() { 
    new FlightSegment{ ClassName = "B"},
    new FlightSegment { ClassName = "C"}
}; 
var result = list1.Intersect(list2, new FlightComparer());

这将返回仅包含一个元素FlightSegment { ClassName = "B" }的集合。

使用这个想法和Aggregate,您可以根据属性获取一组列表的交集:

var intersection = listOfLists.Aggregate((previousList, nextList) => previousList.Intersect(nextList, new FlightComparer() ).ToList());