C# - elegant way of partitioning a list?

前端 未结 11 728
情歌与酒
情歌与酒 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 05:11

    Here is an extension method that will do what you want:

    public static IEnumerable> Partition(this IList source, Int32 size)
    {
        for (int i = 0; i < (source.Count / size) + (source.Count % size > 0 ? 1 : 0); i++)
            yield return new List(source.Skip(size * i).Take(size));
    }
    

    Edit: Here is a much cleaner version of the function:

    public static IEnumerable> Partition(this IList source, Int32 size)
    {
        for (int i = 0; i < Math.Ceiling(source.Count / (Double)size); i++)
            yield return new List(source.Skip(size * i).Take(size));
    }
    

提交回复
热议问题