Convert string to List 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?

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

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

Or even cleaner by Dan’s suggestion:

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

Method 2

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

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

Method 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>();

Method 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();

Method 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

Method 6

If you already have a list and want to add values from a delimited string, you can use AddRange or InsertRange. For example:

existingList.AddRange(names.Split(','));

Method 7

string given="Welcome To Programming";
List<string> listItem= given.Split(' ').ToList();//Split according to space in the string and added into the list

output:

Welcome

To 

Programming

Method 8

Use the Stringify.Library nuget package

//Default delimiter is ,
var split = new StringConverter().ConvertTo<List<string>>(names);

//You can also have your custom delimiter for e.g. ;
var split = new StringConverter().ConvertTo<List<string>>(names, new ConverterOptions { Delimiter = ';' });


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x