LINQ - 在 IEnumerable 中选择第二项 [英] LINQ - selecting second item in IEnumerable

查看:29
本文介绍了LINQ - 在 IEnumerable 中选择第二项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有

string[] pkratio="1:2:6".Split(':');

var items = pkgratio.OrderByDescending(x => x);

我想选择中间值并想出了这个.这是在 IEnumberable 中选择第二个值的正确方法吗?

I want to select the middle value and have come up with this. Is this a correct way to select the second value in an IEnumberable?

pkgratio.Skip(1).Take(1).First();

推荐答案

虽然你的方法可行,但最直接的方法是使用数组的索引并引用第二项(在索引 1 处,因为索引从零开始,对于第一个元素):pkratio[1]

While what you have works, the most straightforward way would be to use the array's index and reference the second item (at index 1 since the index starts at zero for the first element): pkgratio[1]

Console.WriteLine(pkgratio[1]);

一个更完整的例子:

string[] pkgratio = "1:2:6".Split(':');

for (int i = 0; i < pkgratio.Length; i++)
    Console.WriteLine(pkgratio[i]);

使用 IEnumerable 你有什么,或者你可以使用 ElementAt 方法:

With an IEnumerable<T> what you have works, or you could directly get the element using the ElementAt method:

// same idea, zero index applies here too
var elem = result.ElementAt(1);

这是您的 IEnumerable 示例.请注意,AsEnumerable() 调用是为了强调针对 IEnumerable 的示例作品.您实际上可以对 Splitstring[] 数组结果使用 ElementAt,但使用前面显示的索引器效率更高.

Here is your sample as an IEnumerable<string>. Note that the AsEnumerable() call is to emphasize the sample works against an IEnumerable<string>. You can actually use ElementAt against the string[] array result from Split, but it's more efficient to use the indexer shown earlier.

var pkgratio = "1:2:6".Split(':').AsEnumerable();
Console.WriteLine(pkgratio.ElementAt(1));

这篇关于LINQ - 在 IEnumerable 中选择第二项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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