C# - elegant way of partitioning a list?

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

    var yourList = new List { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11 };
    var groupSize = 4;
    
    // here's the actual query that does the grouping...
    var query = yourList
        .Select((x, i) => new { x, i })
        .GroupBy(i => i.i / groupSize, x => x.x);
    
    // and here's a quick test to ensure that it worked properly...
    foreach (var group in query)
    {
        foreach (var item in group)
        {
            Console.Write(item + ",");
        }
        Console.WriteLine();
    }
    

    If you need an actual List> rather than an IEnumerable> then change the query as follows:

    var query = yourList
        .Select((x, i) => new { x, i })
        .GroupBy(i => i.i / groupSize, x => x.x)
        .Select(g => g.ToList())
        .ToList();
    

提交回复
热议问题