GroupBy中的内存节省



对许多项目(GB)运行LINQ to Objects 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实现。

GroupByChanges的实现变化很小——只需更改currentList的赋值,将密钥传递给Grouping构造函数:

Grouping<TKey, TElement> currentGroup = new Grouping<TKey, TElement>(currentKey)
    { iterator.Current };

您的问题非常具体。你不太可能找到一个已经这样做的图书馆。如果你的物品是按你用来分组的键排序的,那么自己对这个列表进行"分组"几乎是一项微不足道的任务。

您可以轻松地自己实现它:

public static class Extensions
{
    public static IEnumerable<IGrouping<TKey, TSource>> GroupByAlreadyOrdered<TSource, TKey>(this IEnumerable<TSource> source, Func<TSource, TKey> keySelector)
    {
        return source.GroupByAlreadyOrdered(keySelector, null);
    }
    public static IEnumerable<IGrouping<TKey, TSource>> GroupByAlreadyOrdered<TSource, TKey>(this IEnumerable<TSource> source, Func<TSource, TKey> keySelector, IEqualityComparer<TKey> comparer)
    {
        TKey currentKey = default(TKey);
        bool first = true;
        List<TSource> currentGroup = null;
        comparer = comparer ?? EqualityComparer<TKey>.Default;
        foreach (var item in source)
        {
            TKey key = keySelector(item);
            if (first || !comparer.Equals(key, currentKey))
            {
                if (currentGroup != null && currentGroup.Any())
                {
                    yield return new Grouping<TKey, TSource>(currentKey, currentGroup);
                }
                currentGroup = new List<TSource>();
            }
            currentGroup.Add(item);
            first = false;
            currentKey = key;
        }
        // Last group
        if (currentGroup != null && currentGroup.Any())
        {
            yield return new Grouping<TKey, TSource>(currentKey, currentGroup);
        }
    }
    private class Grouping<TKey, TElement> : IGrouping<TKey, TElement>
    {
        private readonly TKey _key;
        private readonly IEnumerable<TElement> _elements;
        public Grouping(TKey key, IEnumerable<TElement> elements)
        {
            _key = key;
            _elements = elements;
        }
        public TKey Key
        {
            get { return _key; }
        }
        public IEnumerator<TElement> GetEnumerator()
        {
            return _elements.GetEnumerator();
        }
        IEnumerator IEnumerable.GetEnumerator()
        {
            return GetEnumerator();
        }
    }
}

类似Thomas,但稍快

public static IEnumerable<IGrouping<TKey, TSource>> FastGroupBy<TSource, TKey>(
    this IEnumerable<TSource> source,
    Func<TSource, TKey> keySelector)
{
    using (var enumerator = source.GetEnumerator())
    {
        if (enumerator.MoveNext())
        {
            Grouping<TKey, TSource> grouping;
            List<TSource> list = new List<TSource>();
            TKey key = keySelector(enumerator.Current);
            list.Add(enumerator.Current);
            while (enumerator.MoveNext())
            {
                var currentKey = keySelector(enumerator.Current);
                if (key.Equals(currentKey))
                {
                    list.Add(enumerator.Current);
                    continue;
                }
                grouping = new Grouping<TKey, TSource>(key, list);
                yield return grouping;
                key = currentKey;
                list = new List<TSource>();
                list.Add(enumerator.Current);
            }
            grouping = new Grouping<TKey, TSource>(key, list);
            yield return grouping;
        }
    }
}

相关内容

  • 没有找到相关文章

最新更新