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

后端 未结 6 603
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:31

    The problem is that you're calling List.Reverse() which returns void.

    You could either do:

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

    or:

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

    The latter is more expensive, as reversing an arbitrary IEnumerable involves buffering all of the data and then yielding it all - whereas List can do all the reversing "in-place". (The difference here is that it's calling the Enumerable.Reverse() extension method, instead of the List.Reverse() instance method.)

    More efficient yet, you could use:

    string[] namesArray = "Tom,Scott,Bob".Split(',');
    List namesList = new List(namesArray.Length);
    namesList.AddRange(namesArray);
    namesList.Reverse();
    

    This avoids creating any buffers of an inappropriate size - at the cost of taking four statements where one will do... As ever, weigh up readability against performance in the real use case.

提交回复
热议问题