繁体   English   中英

IEnumerable的 <IGrouping> 到IEnumerable <List>

[英]IEnumerable<IGrouping> to IEnumerable<List>

所以我有这个:

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());

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

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

我认为解决方案更简单。

IGrouping是IEnumerable和IEnumerable <T>。

以下是签名:

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

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM