-2

I believe this is another easy one for you LINQ masters out there. Is there any way I can separate a List into several separate lists of Some Object, using the item index as the delimiter of each split?

Let me exemplify: I have a List<T> and I need a List<List<T>> or List<T>[], so that each of these resulting lists will contain a group of 3 items of the original list (sequentially).

example:

Original List: [cat, dog, pane, wolf, pig, sun, queen, fox, x'mas, yak, ice, mark, cold] Resulting lists: [[cat, dog, pane], [wolf, pig, sun], [queen, fox, x'mas], [yak, ice, mark], [cold]]

Patrick McDonald
  • 64,141
  • 14
  • 108
  • 120

2 Answers2

0

Just a naive fancy:

var animals = new[] { "cat", "dog", "pane", "wolf", "pig", "sun", "queen", "fox", "x'mas", "yak", "ice", "mark", "cold" };
var grouped = Enumerable.Range(0, animals.Length)
                        .Where(i => i%3 == 0)
                        .Select(i => animals.Skip(i).Take(3).ToList())
                        .ToList();
mshsayem
  • 17,557
  • 11
  • 61
  • 69
0

You can use the integer division trick with GroupBy:

List<List<string>> lists = originalList
    .Select((s, index) => new { String = s, Index = index})
    .GroupBy(x => x.Index / 3)
    .Select(g => g.Select(x => x.String).ToList())
    .ToList();

Integer division in C# truncates the remainder, so 0,1,2 / 3 all belong to the zero-group and 3,4,5 / 3 to the one-group and so on.

Tim Schmelter
  • 450,073
  • 74
  • 686
  • 939