【发布时间】:2012-05-01 23:09:30
【问题描述】:
我一次又一次地遇到这个问题:如何通过包含其他对象的列表对对象列表进行分组?
我有一个A 类型的对象列表,每个对象都有一个属性(我们称之为ListProp),它也是一个列表。 ListProp 具有 B 类型的元素。在ListProp 中有多个A 类型的元素与B-objects 相同,但ListProp 属性引用因元素而异。如何以最快的方式对这些 A-objects 进行分组,ListProp 中的 B-objects 相同?
示例代码:
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; }
}
【问题讨论】:
-
为什么最后一个应该在第三组?它应该放在第一位,不是吗?
-
因为元素的数量也应该相同。 0,1 != 0,1,1
-
好吧,这是不正确的编辑。立即清除。