この問題に何度も遭遇します。他のオブジェクトのリストを含むオブジェクトのリストをグループ化するにはどうすればよいですか?
タイプのオブジェクトのリストがありA、これらの各オブジェクトには、リストでもあるプロパティ(それを呼び出しましょうListProp)があります。ListPropタイプの要素がありBます。Aには同じB-objects を持つtype の要素が複数ありますListPropが、ListPropプロパティ参照は要素ごとに異なります。これらの -objects を最速の方法でグループ化Aするにはどうすればよいですか?BListProp
サンプルコード:
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; }
}