Convert string to List<string> in one line?

C#asp.netListGenericsString

C# Problem Overview


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?

C# Solutions


Solution 1 - C#

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

Or even cleaner by Dan's suggestion:

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

Solution 2 - C#

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

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

Solution 3 - C#

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 - C#

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 - C#

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

Solution 6 - C#

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(','));

Solution 7 - C#

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

Solution 8 - C#

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 = ';' });

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionBrian David BermanView Question on Stackoverflow
Solution 1 - C#Matt GreerView Answer on Stackoverflow
Solution 2 - C#Nathan AndersonView Answer on Stackoverflow
Solution 3 - C#KingOfHypocritesView Answer on Stackoverflow
Solution 4 - C#Ashish NeupaneView Answer on Stackoverflow
Solution 5 - C#Carlos EView Answer on Stackoverflow
Solution 6 - C#c32hedgeView Answer on Stackoverflow
Solution 7 - C#Maghalakshmi SaravanaView Answer on Stackoverflow
Solution 8 - C#Mithun BasakView Answer on Stackoverflow