gpt4 book ai didi

c# - 如何根据属性获得两个类的交集

转载 作者:行者123 更新时间:2023-12-03 03:05:47 25 4
gpt4 key购买 nike

我有这门课

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

我想获得具有通用ClassNameFlightSegments

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>

最佳答案

您可以使用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()); 

关于c# - 如何根据属性获得两个类的交集,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36849683/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com