C# - elegant way of partitioning a list?

前端 未结 11 707
情歌与酒
情歌与酒 2020-12-01 04:36

I\'d like to partition a list into a list of lists, by specifying the number of elements in each partition.

For instance, suppose I have the list {1, 2, ... 11}, and

11条回答
  •  庸人自扰
    2020-12-01 04:59

    To avoid multiple checks, unnecessary instantiations, and repetitive iterations, you could use the code:

    namespace System.Collections.Generic
    {
        using Linq;
        using Runtime.CompilerServices;
    
        public static class EnumerableExtender
        {
            [MethodImpl(MethodImplOptions.AggressiveInlining)]
            public static bool IsEmpty(this IEnumerable enumerable) => !enumerable?.GetEnumerator()?.MoveNext() ?? true;
    
            public static IEnumerable> Partition(this IEnumerable source, int size)
            {
                if (source == null)
                    throw new ArgumentNullException(nameof(source));
                if (size < 2)
                    throw new ArgumentOutOfRangeException(nameof(size));
                IEnumerable items = source;
                IEnumerable partition;
                while (true)
                {
                    partition = items.Take(size);
                    if (partition.IsEmpty())
                        yield break;
                    else
                        yield return partition;
                    items = items.Skip(size);
                }
            }
        }
    }
    

提交回复
热议问题