Create List of Tuples from List using LINQ

房东的猫 提交于 2019-12-12 08:56:09

问题


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!


回答1:


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();



回答2:


Maybe this will help someone.

var pairs = from p in TheListOfAllLists select (
new Tuple<string, string>( p.ParameterName,p.Value.ToString()));


来源:https://stackoverflow.com/questions/16892461/create-list-of-tuples-from-list-using-linq

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!