14

So I have this:

IEnumerable<IGrouping<UInt64, MyObject>> groupedObjects = myObjectsResults.GroupBy(x => x.Id);

The question is, how do I turn this result into an IEnumerable<List<MyObject>>?

This is as far as I could take it:

IEnumerable<List<MyObject>> groupedObjects = (myObjectsResults.GroupBy(x => x.Id).SelectMany(group => group).ToList());

which is obviously incorrect. Any ideas?

NetMage
  • 26,163
  • 3
  • 34
  • 55
Doug Peters
  • 529
  • 2
  • 8
  • 17

3 Answers3

12
IEnumerable<List<MyObject>> groupedObjects = myObjectsResults.GroupBy(x => x.Id)
                                            .Select(group => group.ToList())
                                            .ToList();
L.B
  • 114,136
  • 19
  • 178
  • 224
  • 1
    I have the same problem but my collection is too big (Millions of elements) so I cannot call .ToList, what do you suggest please ?! – tobiak777 Dec 29 '14 at 16:58
  • @red2nb Just use `myObjectsResults.GroupBy(x => x.Id)`, Later you can iterate on it using foreach loop.(*In fact, nested two foreach loops*) – L.B Dec 29 '14 at 18:13
6

I think the solution is even simpler.

IGrouping IS an IEnumerable and IEnumerable<T>.

Below is the signature:

#region Assembly System.Core.dll, v4.0.0.0
// C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.5\System.Core.dll
#endregion

using System.Collections;
using System.Collections.Generic;

namespace System.Linq
{
  // Summary:
  //     Represents a collection of objects that have a common key.
  //
  // Type parameters:
  //   TKey:
  //     The type of the key of the System.Linq.IGrouping<TKey,TElement>.This type
  //     parameter is covariant. That is, you can use either the type you specified
  //     or any type that is more derived. For more information about covariance and
  //     contravariance, see Covariance and Contravariance in Generics.
  //
  //   TElement:
  //     The type of the values in the System.Linq.IGrouping<TKey,TElement>.
  public interface IGrouping<out TKey, out TElement> : IEnumerable<TElement>, IEnumerable
  {
    // Summary:
    //     Gets the key of the System.Linq.IGrouping<TKey,TElement>.
    //
    // Returns:
    //     The key of the System.Linq.IGrouping<TKey,TElement>.
    TKey Key { get; }
  }
}
John Zabroski
  • 2,212
  • 2
  • 28
  • 54
0

Another Comfortable Solution is to use a dictionary:

IEnumerable<IGrouping<UInt64, MyObject>> groupedObjects = myObjectsResults.GroupBy(x => x.Id);
Dictionary<UInt64, List<MyObject>> objectGroups = groupedObjects.ToDictionary(group => group.Key, group => group.ToList());
efkah
  • 1,628
  • 16
  • 30