LINQ - selecting second item in IEnumerable

C#Linq.Net 3.5C# 3.0

C# Problem Overview


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

C# Solutions


Solution 1 - C#

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

Solution 2 - C#

I don't think you need to .Take(1).

pkgratio.Skip(1).First()

Solution 3 - C#

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

Solution 4 - C#

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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionJonView Question on Stackoverflow
Solution 1 - C#Ahmad MageedView Answer on Stackoverflow
Solution 2 - C#Cheng ChenView Answer on Stackoverflow
Solution 3 - C#BeRecursiveView Answer on Stackoverflow
Solution 4 - C#Jason PunyonView Answer on Stackoverflow