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

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

问题描述

的String [] pkgratio =1:2:6.Split(':');

  VAR项目= pkgratio.OrderByDescending(X => X);
 

我要选择的中间值,并想出了这一点。这是选择一个IEnumberable的第二值的正确方法是什么?

  pkgratio.Skip(1)。取(1)。首先();
 

解决方案

虽然你有什么工作,最简单的方法是使用数组的索引并引用第二项(在索引1以来,该指数开始于零第一个元素): pkgratio [1]

  Console.WriteLine(pkgratio [1]);
 

一个更完整的例子:

 的String [] pkgratio =1:2:6.Split(:);

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

随着的IEnumerable< T> 你有什么工作,或者你可以直接得到使用的 的ElementAt 方法

  //同样的想法,零点指标也适用于此
变种的elem = result.ElementAt(1);
 

下面是你的样品为的IEnumerable<字符串> 。请注意, AsEnumerable()调用强调样的作品对一个的IEnumerable<字符串> 。实际上,你可以使用的ElementAt 的String [] 阵列结果从分割,但它更有效地使用前面介绍的索引。

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

I have

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

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

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

解决方案

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

A more complete example:

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

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

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

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天全站免登陆