我一次又一次遇到這個問題:如何通過包含其他對象的列表來對一組對象進行分組?如何根據元素列表進行分組?
我有一個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