使用LINQ从列表创建元组列表 [英] Create List of Tuples from List using LINQ

查看:112
本文介绍了使用LINQ从列表创建元组列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用LINQ从列表中创建元组列表,但无法解决该问题.我得到的是外部文件中的各种数据,我正在使用标准方法将各节读取为List<Single>,然后需要将其转换为该列表的顺序元素组列表(其中可能包含一个组中元素的数量可变).换句话说:

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

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

我不知道如何使用LINQ做到这一点,所以我已经恢复到for循环,例如:

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

我根本不担心通用解决方案,我对是否有可能使用LINQ做这种事情感兴趣.它似乎超出了预期的范围,但是我没有足够的感觉来知道这是否是真的.

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.

我的问题是,是否可以使用LINQ完成上述类型的任务.我在用户界面和Google中四处闲逛,但是空无一物!

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!

推荐答案

可以实现(Tuple<Single, Single>的示例),以下解决方案不是很复杂,但是使用循环更清晰-在这种情况下解决方案-效率更高(输入列表被枚举两次). 用C#编写的代码,不知道VB

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

这篇关于使用LINQ从列表创建元组列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆