2

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:

  • Item1(1,1,1);
  • Item2(1,2,2);
  • Item3(1,3,3);
  • Item4(2,4,4);
  • Item5(2,5,5);
  • Item6(2,6,6);
  • Item7(3,7,7);
  • Item8(3,8,8);
  • Item9(3,9,9);

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.

ASh
  • 34,632
  • 9
  • 60
  • 82
Álvaro García
  • 18,114
  • 30
  • 102
  • 193
  • 1
    Duplicate :- http://stackoverflow.com/questions/2697253/using-linq-to-group-a-list-of-objects-into-a-new-grouped-list-of-list-of-objects – user3517179 May 14 '15 at 08:37

2 Answers2

3
List<List<MyType>> myResultList = 
      myOriginalList.GroupBy(x=>x.IDReferenceElement)
                    .Select(gr=>gr.ToList()) // convert each group into List
                    .ToList();
ASh
  • 34,632
  • 9
  • 60
  • 82
1

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")