【问题标题】:IEnumerable<IGrouping> to IEnumerable<List>IEnumerable<IGrouping> 到 IEnumerable<List>
【发布时间】:2014-04-21 00:39:32
【问题描述】:

所以我有这个:

IEnumerable&lt;IGrouping&lt;UInt64, MyObject&gt;&gt; groupedObjects = myObjectsResults.GroupBy(x =&gt; x.Id);

问题是,我如何把这个结果变成IEnumerable&lt;List&lt;MyObject&gt;&gt;

这是我所能接受的:

IEnumerable&lt;List&lt;MyObject&gt;&gt; groupedObjects = (myObjectsResults.GroupBy(x =&gt; x.Id).SelectMany(group =&gt; group).ToList());

这显然是不正确的。有什么想法吗?

【问题讨论】:

    标签: c# list linq igrouping


    【解决方案1】:

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

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

    【讨论】:

      【解决方案2】:

      我认为解决方案更简单。

      IGrouping 是一个 IEnumerable 和 IEnumerable

      下面是签名:

      #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; }
        }
      }
      

      【讨论】:

        【解决方案3】:
        IEnumerable<List<MyObject>> groupedObjects = myObjectsResults.GroupBy(x => x.Id)
                                                    .Select(group => group.ToList())
                                                    .ToList();
        

        【讨论】:

        • 我有同样的问题,但我的集合太大(数百万个元素),所以我无法调用 .ToList,请问您有什么建议?!
        • @red2nb 就用myObjectsResults.GroupBy(x =&gt; x.Id),以后可以用foreach循环对其进行迭代。(其实嵌套了两个foreach循环
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2014-07-30
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-02-24
        • 2020-12-07
        • 1970-01-01
        相关资源
        最近更新 更多