6

Is it possible with single LINQ query to convert a single dimensional array like this:

string[] source = new string[] { "1", "Name1", "Value1", "2", "Name2", "Value2", "3", "Name3", "Value3" };

into IEnumerable<> of three objects containing three properties, build from each three successive strings?

Konrad Kokosa
  • 16,563
  • 2
  • 36
  • 58
  • 2
    If it's possible, I want to see it; gonna be some pretty good looking code. – frenchie Nov 17 '13 at 11:13
  • For reference, some related questions can be found at http://stackoverflow.com/questions/1290451/how-to-group-items-by-index-c-sharp-linq and http://stackoverflow.com/questions/860305/how-to-use-linq-to-group-every-n-number-of-rows. – Stuart Golodetz Nov 17 '13 at 11:21

1 Answers1

12

Yes, it's possible, you could group them by the index in the array:

string[] source = new string[] { "1", "Name1", "Value1", "2", "Name2", "Value2", "3", "Name3", "Value3" };
var result = source
    .Select((element, index) => new { element, index })
    .GroupBy(x => x.index / 3)
    .Select(x => new
    {
        Id = x.ElementAt(0).element,
        Name = x.ElementAt(1).element,
        Value = x.ElementAt(2).element
    }).ToList();

// at this stage the result variable will represent a list of 3 elements where
// each element is an anonymous object containing the 3 properties. You could of course
// replace the anonymous object with a model if you intend to use the result of the query
// outside of the scope of the method it is being executed in.

Obviously in this example, there's no error checking. It is something you might consider doing before running the LINQ query. The length of the array should be divisible by 3 obviously.

Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928