Convert string to List<string> in one line?
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?
List<string> result = names.Split(new char[] { ',' }).ToList();
Or even cleaner by Dan's suggestion:
List<string> result = names.Split(',').ToList();
The List<T>
has a constructor that accepts an IEnumerable<T>
:
List<string> listOfNames = new List<string>(names.Split(','));
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>();
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();
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