0

Possible Duplicate:
Split List into Sublists with LINQ

I'm looking for some way to split an enumerable into three enumerables using LINQ, such that each successive item in the input is in the next sublist in in the sequence. So input

{"a", "b", "c", "d", "e", "f", "g", "h"}

would result in

{"a", "d", "g"}, {"b", "e", "h"}, {"c", "f"}

I've done it this way but I'm sure there must be a way to express this more elegantly using LINQ.

var input = new List<string> {"a", "b", "c", "d", "e", "f", "g", "h"};
var list = new List<string>[3];

for (int i = 0; i < list.Length; i++)
    list[i] = new List<string>();

int column = 0;
foreach (string letter in input)
{
    list[column++].Add(letter);
    if (column > 2) column = 0;
}
Community
  • 1
  • 1
Steve Crane
  • 4,340
  • 5
  • 40
  • 63
  • 1
    http://stackoverflow.com/questions/419019/split-list-into-sublists-with-linq – d.lavysh Jul 26 '12 at 13:29
  • Check this link, http://peshir.blogspot.nl/2011/02/example-of-c-lazy-functional.html – Maarten Jul 26 '12 at 13:42
  • Please don't edit the automatically entered duplicate question link. It's automated and should the question ever be reopened the system will not be able to remove it. Rather make your changes below the clearly marked indicators of the automatic insert. – BinaryMisfit Jul 27 '12 at 11:35

1 Answers1

4

This is what you are looking for: (Splits by columns) Modified based on the previous posts

The key difference is in the group by, using mod instead of division.

Also I made it generic so it gives you back the proper type (as opposed to "object typed" code). You can just use type inference with generics.

public static IEnumerable<IEnumerable<T>> SplitColumn<T>( IEnumerable<T> source ) {
    return source
        .Select( ( x, i ) => new { Index = i, Value = x } )
        .GroupBy( x => x.Index % 3 )
        .Select( x => x.Select( v => v.Value ).ToList() )
        .ToList();
}
James
  • 2,445
  • 2
  • 25
  • 35
  • I actually saw that question but it was asking for each of the sublists to be sequential so I ignored it. Strange that this is the accepted answer there when it correctly solves my problem, not the one asked in that question. – Steve Crane Jul 26 '12 at 13:46
  • @SteveCrane I'm just thinking if I can make this a tad more re-usable. How do you normally specify the split size? (Items per sublist, or number of sublists?) – James Jul 26 '12 at 13:49
  • If you wanted this to be a reusable function then number of sublists (columns) would be what you want. – Steve Crane Jul 26 '12 at 14:55
  • Seems I was wrong in my comment above. Since this question was closed as a duplicate I've re-looked at both and realised there is a subtle difference in the accepted solutions that result in differently ordered results. – Steve Crane Jul 27 '12 at 09:03