12

所以我有这个:

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

问题是,我如何把这个结果变成一个IEnumerable<List<MyObject>>

这是我所能接受的:

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

这显然是不正确的。有任何想法吗?

4

3 回答 3

12
IEnumerable<List<MyObject>> groupedObjects = myObjectsResults.GroupBy(x => x.Id)
                                            .Select(group => group.ToList())
                                            .ToList();
于 2014-03-15T16:52:23.553 回答
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; }
  }
}
于 2014-10-06T21:38:11.617 回答
0

另一个舒适的解决方案是使用字典:

IEnumerable<IGrouping<UInt64, MyObject>> groupedObjects = myObjectsResults.GroupBy(x => x.Id);
Dictionary<UInt64, List<MyObject>> objectGroups = groupedObjects.ToDictionary(group => group.Key, group => group.ToList());
于 2018-03-15T09:58:04.107 回答