我一次又一次遇到这个问题:如何通过包含其他对象的列表来对一组对象进行分组?如何根据元素列表进行分组?
我有一个A
类型的对象列表,每个对象都有一个属性(我们称之为ListProp
),这也是一个列表。 ListProp
具有B
类型的元素。有A
类型的多个元素具有相同的B
-对象ListProp
,但ListProp
属性参考因元素而异。如何将这些A
对象分组为最快的方式,B
-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; }
}
为什么最后应该是在第三组?它应该在第一,我不应该? – abatishchev 2012-04-20 11:28:25
因为元素的数量也应该相同。 0,1!= 0,1,1 – germanSharper 2012-04-20 11:45:16
好吧,那是不正确的编辑。现在清除。 – abatishchev 2012-04-20 11:47:51