Split List into Sublists with LINQ

前端 未结 30 2452
灰色年华
灰色年华 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 06:55

    I took the primary answer and made it to be an IOC container to determine where to split. (For who is really looking to only split on 3 items, in reading this post while searching for an answer?)

    This method allows one to split on any type of item as needed.

    public static List> SplitOn(List main, Func splitOn)
    {
        int groupIndex = 0;
    
        return main.Select( item => new 
                                 { 
                                   Group = (splitOn.Invoke(item) ? ++groupIndex : groupIndex), 
                                   Value = item 
                                 })
                    .GroupBy( it2 => it2.Group)
                    .Select(x => x.Select(v => v.Value).ToList())
                    .ToList();
    }
    

    So for the OP the code would be

    var it = new List()
                           { "a", "g", "e", "w", "p", "s", "q", "f", "x", "y", "i", "m", "c" };
    
    int index = 0; 
    var result = SplitOn(it, (itm) => (index++ % 3) == 0 );
    

提交回复
热议问题