C# Syntax - Split String into Array by Comma, Convert To Generic List, and Reverse Order

后端 未结 6 587
Happy的楠姐
Happy的楠姐 2020-12-07 19:49

What is the correct syntax for this:

IList names = \"Tom,Scott,Bob\".Split(\',\').ToList().Reverse();

What am I

6条回答
  •  [愿得一人]
    2020-12-07 20:19

    If you are trying to

    1. Use multiple delimiters
    2. Filter any empty strings
    3. Trim leading/trailing spaces

    following should work:

    string str = "Tom Cruise, Scott, ,Bob | at";
    IEnumerable names = str
                                .Split(new char[]{',', '|'})
                                .Where(x=>x!=null && x.Trim().Length > 0)
                                .Select(x=>x.Trim());
    

    Output

    • Tom
    • Cruise
    • Scott
    • Bob
    • at

    Now you can obviously reverse the order as others suggested.

提交回复
热议问题