Create a list of Tuples from the list using LINQ

advertisements

I'm trying to create a list of tuples from a list using LINQ, but can't work out how to do it. What I've got is various data in an external file, which I'm reading sections using a standard method into a List<Single>, I then need to turn this into lists of groups of sequential elements of this list (which may have a variable number of elements in the groups). To state it another way:

List<Single> with n elements goes to List<Tuple<Single, Single>> with (n/2) elements

or

List<Single> with n elements goes to List<Tuple<Single, Single, Single>> with (n/3) elements

I couldn't work out how to do this with LINQ, so I've reverted to a for loop like, for example, so:

For i As Integer = 0 To CType(coords.Item2.Count / 3, Integer) Step 3
    normalList.Add( _
        New Tuple(Of Single, Single, Single)( _
            coords.Item2.Item(i), _
            coords.Item2.Item(i + 1), _
            coords.Item2.Item(i + 2) _
        ) _
    )
Next i

EDIT: I'm not at all worried about a generic solution, I'm interested in if it's possible to do this type of thing using LINQ. It seems to be outside the score of what it's intended for, but I don't have enough of a feel to know if this is true.

My question is is is it possible to accomplish the above type of task using LINQ. I've bashed around in the UI and google but have come up empty!


It can be achieved (example for Tuple<Single, Single>) and the following solution isn't very complex, but using loop is clearer and - in case of this particular solution - more efficient (the input list is enumerated twice). Code in C#, don't know VB

var even = inputList.Where((elem, ind) => ind % 2 == 0);
var odd = inputList.Where((elem, ind) => ind % 2 == 1);
var outputList = even.Zip(odd, (a, b) => new Tuple<Single, Single>(a, b)).ToList();