简体   繁体   中英

Get Index of a String Array after Split using LINQ

I am trying to get the third index of my splitted string. But I cannot get the exact value using LINQ. I am trying to get the third index value which is "CC":

string strInput = @"AA BB CC DD EE";
var xRes = strInput.Split(' ').Skip(1).Take(1).Select(c => c).ToArray();

The last line was able to get the exact third array. But I wasn't able to convert it to string. If I do this:

var xRes = strInput.Split(' ').Skip(2).Take(1).Select(c => c[0].ToString()).ToString();

I get this instead:

System.Linq.Enumerable+WhereSelectEnumerableIterator`2[System.String,System.String]

How about

string strInput = @"AA BB CC DD EE";
var xRes = strInput.Split(' ')[2];

You don't need to use LINQ to do that.

If you insist in using LINQ, you can do it using ElementAt .

var xRes = strInput.Split(' ').ElementAt(2);

Or Skip followed by First

var xRes = strInput.Split(' ').Skip(2).First();

您不希望像这样建议使用索引:

var xRes = strInput.Split(' ').Skip(2).First()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM