Reputation: 19396
I have a a list (OriginalList) with elements of type MyType. My Type is:
MyType
{
long IDReferenceElement;
long IDElement;
string value;
}
So I would like to separate in lists each group of elements, where each group has the elements with the same IDReferenceElement.
For example, a list of lists, each list of the main list has only the elements of the same group.
List<List<MyType>>
An example, I have a original list with this elements:
I would like to get three lists:
List1 with the items: - Item1(1,1,1); - Item2(1,2,2); - Item3(1,3,3);
List2: - Item4(2,4,4); - Item5(2,5,5); - Item6(2,6,6);
List3: - Item7(3,7,7); - Item8(3,8,8); - Item9(3,9,9);
To get it, I am trying something like that:
List<List>> myResultList = myOriginalList.GroupBy(x=>x.IDReferenceElement).ToList();
It does not work, because a group element is not a list. I would like to know how to access each group of the grouping and to covert to a list.
Thanks so much.
Upvotes: 2
Views: 177
Reputation: 713
Another approach would be to use a lookup
var myResultsLookup = myOriginalList.ToLookup(myType => myType.IDReferenceElement);
Now each subset of data can be accessed using the IDReferenceElement value as the key
var results = myResultsLookup[1];
using your test data results will contain the elements (1,1,"1"), (1,2,"2") and (1,3,"3")
Upvotes: 1
Reputation: 35730
List<List<MyType>> myResultList =
myOriginalList.GroupBy(x=>x.IDReferenceElement)
.Select(gr=>gr.ToList()) // convert each group into List
.ToList();
Upvotes: 3