Mi imbatto ancora e ancora su questo problema: come posso raggruppare un elenco di oggetti tramite un elenco contenente altri oggetti?Come posso raggruppare in base a un elenco di elementi?
Ho una lista di oggetti di tipo A
e ognuno di questi oggetti ha una proprietà (chiamiamolo ListProp
) che è anche una lista. ListProp
ha elementi del tipo B
. Esistono più elementi di tipo A
con gli stessi oggetti B
in ListProp
, ma il riferimento di proprietà ListProp
differisce da elemento a elemento. Come posso raggruppare questi oggetti A
nel modo più rapido, dove gli oggetti B
sono identici in ListProp
?
codice di esempio:
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; }
}
Perché l'ultimo dovrebbe essere nel terzo gruppo? Dovrebbe essere in prima, non dovrei? – abatishchev
Perché il numero di elementi dovrebbe essere lo stesso. 0,1! = 0,1,1 – germanSharper
Ok questa è stata una modifica impropria. Chiaro ora – abatishchev