简体   繁体   中英

split array and get last value of each index

I have a string which looks like this

string sortOrder= "download-15104,download-15103,download-15105,download-15106,download-15107,download-16104,download-16105";

And i want just ids . So , i did this

var ids= new List<int>();
var sortOrderArray = sortOrder.Split(',');
foreach (var item in sortOrderArray)
{
    var obj = item.Split('-');
    ids.Add(int.Parse(obj[1]));
}

Is there any other way to do this and do this quick ?

You could use LINQ:

var ids = input.Split(',').Select(x => int.Parse(x.Split('0')[1])).ToList();

But, it will not be faster . It uses loops internally anyway. It may just be much more readable.

var ids=Regex.Matches(sortOrder,@"\d+(?=,|$)")
             .Cast<Match>()
             .Select(m=>int.Parse(m.Value));

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