Split List into Sublists with LINQ

前端 未结 30 3192
灰色年华
灰色年华 2020-11-21 06:26

Is there any way I can separate a List into several separate lists of SomeObject, using the item index as the delimiter of each s

30条回答
  •  天命终不由人
    2020-11-21 07:01

    Here's a list splitting routine I wrote a couple months ago:

    public static List> Chunk(
        List theList,
        int chunkSize
    )
    {
        List> result = theList
            .Select((x, i) => new {
                data = x,
                indexgroup = i / chunkSize
            })
            .GroupBy(x => x.indexgroup, x => x.data)
            .Select(g => new List(g))
            .ToList();
    
        return result;
    }
    

提交回复
热议问题