views:

179

answers:

5

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();
+12  A: 

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

Your title mentions IEnumerable but you have a string array. If you had an IEnumerable<string> then what you have works, or better yet you would use:

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

Here is your sample as an IEnumerable<string>:

var pkgratio = "1:2:6".Split(':').AsEnumerable();
Console.WriteLine(pkgratio.ElementAt(1));
Ahmad Mageed
Ah, you beat me to the punch by like 10 seconds.
Andrew Barrett
+6  A: 

pkgratio.ElementAt(1); for your scenario.

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

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

BeRecursive
+2  A: 

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

pkgratio.Skip(1).First()
Danny Chen
+2  A: 

But in this case you have an array, so you can pretty happily get the second item using:

pkgratio[1]
Andrew Barrett
+1  A: 

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.

Jason Punyon