[英]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.