开发者

Memory saving in GroupBy

Running LINQ to Objects GroupBy() method for many items (gigabytes) can be memory consuming. If the IEnumerable<T> is already开发者_Python百科 ordered by the key, we could write an GroupBy that didn't consume as much memory.

Where can I find a library that has such method?


There's nothing in the framework to do this. If you don't need an actual IGrouping<,> you could use this:

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

If you need a full IGrouping<,> implementation it'll be slightly harder - but you could always grab my Edulinq implementation.

The implementation of GroupByChanges would change very little - just change the currentList assignments to pass in the key to the Grouping constructor:

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


Your problem is very specific. It is highly unlikely that you will find a library that already does this. If your items are ordered by the key which you use to group, it is a near-trivial task to 'group' this list yourself.


You could easily implement it yourself:

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

}


Like Thomas' but slightly faster

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜