Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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(); 
like image 608
Jon Avatar asked Sep 13 '10 14:09

Jon


2 Answers

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)); 
like image 81
Ahmad Mageed Avatar answered Nov 05 '22 10:11

Ahmad Mageed


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

pkgratio.Skip(1).First() 
like image 37
Cheng Chen Avatar answered Nov 05 '22 08:11

Cheng Chen