LINQ - selecting second item in IEnumerable

后端 未结 4 629
执念已碎
执念已碎 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: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 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. Note that the AsEnumerable() call is to emphasize the sample works against an IEnumerable. 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));
    

提交回复
热议问题