简体   繁体   中英

LINQ - selecting second item in IEnumerable

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

我认为你不需要。采取.Take(1)

pkgratio.Skip(1).First()

pkgratio.ElementAt(1); for your scenario.

However, your method is only applicable if you were using some data that implemented IQueryable or you needed to take a range of items starting at a specific index eg:

pkgratio.Skip(5).Take(10);

Well, the Take(1) isn't strictly necessary if you're going to just First() it, so I might go with

pkgratio.Skip(1).First();

However, that First() will throw an exception if there no value, so you might want to try FirstOrDefault() and then check for null.

但是在这种情况下你有一个数组,所以你可以很高兴得到第二个项目使用:

pkgratio[1]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM