Chunking a Collection into Groups of Three

Raw data for a LINQ query doesn’t always come in the form you want.  Recently, I had some data like this:

This blog is inactive.
New blog: EricWhite.com/blog

Blog TOC

string[] source = new [] {
"EW",
"Eric",
"8:00",
"DW",
"Dave",
"9:00",
"JA",
"Jim",
"8:00"
};

You want to transform the above collection of strings into a collection of anonymous objects that are easier to work on, so you need to write a query that operates on groups of three.  To solve this problem, you can take advantage that the Select extension method has an overload that passes an index number to the selection function:

string[] source = new [] {
"EW",
"Eric",
"8:00",
"DW",
"Dave",
"9:00",
"JA",
"Jim",
"8:00"
};
var people = source
.Select
(
(s, i) =>
new
{
Value = s,
Chunk = i / 3
}
)
.GroupBy(x => x.Chunk)
.Select
(
g =>
new
{
Initials = g.First().Value,
Name = g.Skip(1).First().Value,
Time = g.Skip(2).First().Value
}
);
foreach (var p in people)
Console.WriteLine(p);

This produces the following output:

{ Initials = EW, Name = Eric, Time = 8:00 }
{ Initials = DW, Name = Dave, Time = 9:00 }
{ Initials = JA, Name = Jim, Time = 8:00 }

This new collection is a whole lot easier to work with.