.net - GroupBy 中的内存节省

标签 .net linq group-by memory-management linq-to-objects

运行 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/

相关文章:

按两列分组的Mysql问题

.net - 无法通过 Exchange 发送电子邮件 : An existing connection was forcibly closed by the remote host

c# - 获取当前应用配置文件的文件路径

c# - 将自定义系统光标重置为正常

c# - Linq 从 List<string> 中包含

sql - 从分组依据中排除列

c# - 在带有 GroupBy 和 Sum 聚合的 ObservableCollection 上使用 LINQ

.net - 类内存堆/引用变量概念

linq - SingleOrDefault()在多个元素上引发异常

c# - linq to sql语法不同但应该得到相同的结果