LINQ - selecting second item in IEnumerable

后端 未结 4 594
执念已碎
执念已碎 2020-12-05 17:11

I have

string[] pkgratio= \"1:2:6\".Split(\':\');

var items = pkgratio.OrderByDescending(x => x);

I want to select

相关标签:
4条回答
  • 2020-12-05 17:27

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

    pkgratio.Skip(1).First()
    
    0 讨论(0)
  • 2020-12-05 17:38

    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));
    
    0 讨论(0)
  • 2020-12-05 17:44

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

    0 讨论(0)
  • 2020-12-05 17:48

    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.

    0 讨论(0)
提交回复
热议问题