Convert string to List<string> in one line?

313,557

Solution 1

List<string> result = names.Split(new char[] { ',' }).ToList();

Or even cleaner by Dan's suggestion:

List<string> result = names.Split(',').ToList();

Solution 2

The List<T> has a constructor that accepts an IEnumerable<T>:

List<string> listOfNames = new List<string>(names.Split(','));

Solution 3

I prefer this because it prevents a single item list with an empty item if your source string is empty:

  IEnumerable<string> namesList = 
      !string.isNullOrEmpty(names) ? names.Split(',') : Enumerable.Empty<string>();

Solution 4

Use Split() function to slice them and ToList() to return them as a list.

var names = "Brian,Joe,Chris";
List<string> nameList = names.Split(',').ToList();

Solution 5

Split a string delimited by characters and return all non-empty elements.

var names = ",Brian,Joe,Chris,,,";
var charSeparator = ",";
var result = names.Split(charSeparator, StringSplitOptions.RemoveEmptyEntries);

https://docs.microsoft.com/en-us/dotnet/api/system.string.split?view=netframework-4.8

Share:
313,557
Brian David Berman
Author by

Brian David Berman

Updated on June 12, 2021

Comments

  • Brian David Berman
    Brian David Berman almost 3 years

    I have a string:

    var names = "Brian,Joe,Chris";
    

    Is there a way to convert this to a List<string> delimited by , in one line?

  • Dan Tao
    Dan Tao over 13 years
    You may have put it there on purpose, but I always leave out the whole new char[] { } part. It's more readable that way, to me at least.
  • Matt Greer
    Matt Greer over 13 years
    @Dan: I agree, and generally I do use the params overload. But for an answer to a question sometimes I feel like verbosity is better. Just a matter of opinion really.
  • Gina Marano
    Gina Marano almost 11 years
    ToList() doesn't seem to be avail anymore?
  • Matt Greer
    Matt Greer almost 11 years
    Did you bring in the System.LINQ namespace?
  • VictorySaber
    VictorySaber over 7 years
    Excellent - no need to import System.Linq