运行 LINQ to 对象 GroupBy()
许多项目(千兆字节)的方法可能会消耗内存。如果IEnumerable<T>
已经按键排序了,我们可以写 GroupBy
没有消耗太多内存。
哪里可以找到具有这种方法的库?
最佳答案
框架中没有任何内容可以执行此操作。如果您不需要实际的IGrouping<,>
你可以使用这个:
static IEnumerable<IList<TElement>> GroupByChanges<TElement, TKey>
(this IEnumerable<TElement> source,
Func<TElement, TKey> projection)
{
// TODO: Argument validation, splitting this into two methods
// to achieve eager validation.
// TODO: Allow a custom comparer to be used, possibly even
// an IComparer<T> instead of an IEqualityComparer<T>
IEqualityComparer<TKey> comparer = EqualityComparer<TKey>.Default;
using (IEnumerator<TElement> iterator = source.GetEnumerator())
{
if (!iterator.MoveNext())
{
yield break;
}
TKey currentKey = projection(iterator.Current);
IList<TElement> currentList = new List<TElement> { iterator.Current };
while (iterator.MoveNext())
{
TKey key = projection(iterator.Current);
if (!comparer.Equals(currentKey, key))
{
yield return currentList;
currentList = new List<TElement>();
}
currentList.Add(iterator.Current);
}
yield return currentList;
}
}
如果您需要完整的IGrouping<,>
实现会稍微困难一些 - 但你总是可以捕获我的 Edulinq implementation .
执行GroupByChanges
变化很小 - 只需更改 currentList
将 key 传递给 Grouping
的分配构造函数:
Grouping<TKey, TElement> currentGroup = new Grouping<TKey, TElement>(currentKey)
{ iterator.Current };
关于.net - GroupBy 中的内存节省,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6097035/