gpt4 book ai didi

c# - LINQ GroupBy 集合

转载 作者:太空狗 更新时间:2023-10-29 20:25:15 26 4
gpt4 key购买 nike

是否可以在 LINQ 中使用集合属性进行 GroupBy?

例如

void Main()
{
var t1 = new Test() { Children = new List<string>() { "one", "two" } };
var t2 = new Test() { Children = new List<string>() { "one", "two" } };
var t3 = new Test() { Children = new List<string>() { "one", "three" } };

var tests = new List<Test>() { t1, t2, t3 };
var anon = from t in tests
select new
{
Children = t.Children
};

anon.GroupBy(t => t.Children).Dump();
}

public class Test
{
public List<string> Children {get;set;}
}

在这个例子中,我希望有两组:

Key: List() { "one", "two" } Value: t1, t2

Key: List() { "one", "three" } Value: t3

我的理解是,匿名类型不是通过引用进行比较,而是通过比较其公共(public)属性的相等性。

然而,实际结果是三组:

Key: List() { "one", "two" } Value: t1

Key: List() { "one", "two" } Value: t2

Key: List() { "one", "three" } Value: t3

如果这不可能,有没有办法得到我想要的结果?

希望解释清楚...

最佳答案

默认情况下,GroupBy 将在按列表(引用类型)分组时使用引用相等性。

由于您每次都有列表的新实例,因此它们不相等。

但是,有一个 overload GroupBy 允许您指定自定义 IEqualityComparer ,这样您就可以实现自己的方式来比较字符串列表,例如。

为了实现这个,有很多other threads这里是关于比较两个列表。

关于c# - LINQ GroupBy 集合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8138515/

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