69

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();
Jon
  • 38,814
  • 81
  • 233
  • 382
  • related to my first ever question: http://stackoverflow.com/questions/1735146/ways-to-get-the-middle-of-a-list-in-haskell – Matt Ellen Sep 13 '10 at 14:03
  • 1
    Using `First()` implies you are confident that an item will actually be at the position you are attempting to access. If there is any doubt, you may wish to use `FirstOrDefault()`. – Anthony Pegram Sep 13 '10 at 14:06

4 Answers4

101

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));
Ahmad Mageed
  • 94,561
  • 19
  • 163
  • 174
52

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

pkgratio.Skip(1).First()
Cheng Chen
  • 42,509
  • 16
  • 113
  • 174
23

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

BeRecursive
  • 6,286
  • 1
  • 24
  • 41
19

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.

Restore the Data Dumps
  • 38,967
  • 12
  • 96
  • 122