Split C# collection into equal parts, maintaining sort

前端 未结 8 1832
野的像风
野的像风 2021-02-19 18:31

I am trying to split a collection into multiple collections while maintaining a sort I have on the collection. I have tried using the following extension method, but it breaks

8条回答
  •  栀梦
    栀梦 (楼主)
    2021-02-19 18:59

    A slightly more clean LINQ approach, for this rather old question:

    public static IEnumerable> Partition(this IEnumerable source, int n)
    {
        var count = source.Count();
    
        return source.Select((x, i) => new { value = x, index = i })
            .GroupBy(x => x.index / (int)Math.Ceiling(count / (double)n))
            .Select(x => x.Select(z => z.value));
    }
    

提交回复
热议问题