ger*_*per 8 .net c# linq group-by
我一次又一次地遇到这个问题:如何通过包含其他对象列表来对对象列表进行分组?
我有一个类型对象的列表,A每个对象都有一个属性(让我们称之为ListProp),这也是一个列表.ListProp有类型的元素B.有多个类型的元素A具有相同的B-objects ListProp,但ListProp属性引用因元素而异.如何A以最快的方式对这些对象进行分组,其中B-objects ListProp是相同的?
示例代码:
class Program
{
static void Main(string[] args)
{
var exampleList = new List<A>
{
// Should be in first group
new A { ListProp = new List<B>
{
new B { Prop = new C { Number = 0 }},
new B { Prop = new C { Number = 1 }}
}},
// Should be in first group
new A { ListProp = new List<B>
{
new B { Prop = new C { Number = 0 }},
new B { Prop = new C { Number = 1 }}
}},
// Should be in second group
new A { ListProp = new List<B>
{
new B { Prop = new C { Number = 0 }},
new B { Prop = new C { Number = 1 }},
new B { Prop = new C { Number = 1 }}
}},
// Should be in third group
new A { ListProp = new List<B>
{
new B { Prop = new C { Number = 0 }},
new B { Prop = new C { Number = 0 }}
}}
};
// Doesn't work because the reference of ListProp is always different
var groupedExampleList = exampleList.GroupBy(x => x.ListProp);
}
}
class C
{
public int Number { get; set; }
public override bool Equals(object o)
{
if (o is C)
return Number.Equals(((C)o).Number);
else
return false;
}
}
class B
{
public C Prop { get; set; }
}
class A
{
public IList<B> ListProp { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
您可以IEqualityComparer<List<B>>在其他GroupBy重载中实现和使用它.
public class ListOfBEqualityComparer : IEqualityComparer<List<B>>
{
public bool Equals(List<B> x, List<B> y)
{
// you can also implement IEqualityComparer<B> and use the overload
return x.SequenceEqual(y);
}
public int GetHashCode(List<B> obj)
{
//implementation of List<T> may not work for your situation
return obj.GetHashCode();
}
}
Run Code Online (Sandbox Code Playgroud)
然后你可以使用过载
var groupedExampleList = exampleList.GroupBy(x => x.ListProp,
new ListOfBEqualityComparer());
Run Code Online (Sandbox Code Playgroud)