Grouping lists into groups of X items per group

后端 未结 5 760
一个人的身影
一个人的身影 2020-12-09 22:54

I\'m having a problem knowing the best way to make a method to group a list of items into groups of (for example) no more than 3 items. I\'ve created the method below, but w

5条回答
  •  长情又很酷
    2020-12-09 23:51

    Here's one way to do this using LINQ...

    public static IEnumerable> GroupBy
        (this IEnumerable source, int itemsPerGroup)
    {
        return source.Zip(Enumerable.Range(0, source.Count()),
                          (s, r) => new { Group = r / itemsPerGroup, Item = s })
                     .GroupBy(i => i.Group, g => g.Item)
                     .ToList();
    }
    

    Live Demo

提交回复
热议问题