Convert string to List<string> 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>();