[c#] 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?

This question is related to c# asp.net list generics string

The answer is


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

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

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


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

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

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

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

Examples related to c#

How can I convert this one line of ActionScript to C#? Microsoft Advertising SDK doesn't deliverer ads How to use a global array in C#? How to correctly write async method? C# - insert values from file into two arrays Uploading into folder in FTP? Are these methods thread safe? dotnet ef not found in .NET Core 3 HTTP Error 500.30 - ANCM In-Process Start Failure Best way to "push" into C# array

Examples related to asp.net

RegisterStartupScript from code behind not working when Update Panel is used You must add a reference to assembly 'netstandard, Version=2.0.0.0 No authenticationScheme was specified, and there was no DefaultChallengeScheme found with default authentification and custom authorization How to use log4net in Asp.net core 2.0 Visual Studio 2017 error: Unable to start program, An operation is not legal in the current state How to create roles in ASP.NET Core and assign them to users? How to handle Uncaught (in promise) DOMException: The play() request was interrupted by a call to pause() ASP.NET Core Web API Authentication Could not load file or assembly 'CrystalDecisions.ReportAppServer.CommLayer, Version=13.0.2000.0 WebForms UnobtrusiveValidationMode requires a ScriptResourceMapping for jquery

Examples related to list

Convert List to Pandas Dataframe Column Python find elements in one list that are not in the other Sorting a list with stream.sorted() in Java Python Loop: List Index Out of Range How to combine two lists in R How do I multiply each element in a list by a number? Save a list to a .txt file The most efficient way to remove first N elements in a list? TypeError: list indices must be integers or slices, not str Parse JSON String into List<string>

Examples related to generics

Instantiating a generic type Are these methods thread safe? The given key was not present in the dictionary. Which key? Using Java generics for JPA findAll() query with WHERE clause Using Spring RestTemplate in generic method with generic parameter How to create a generic array? Create a List of primitive int? How to have Java method return generic list of any type? Create a new object from type parameter in generic class What is the "proper" way to cast Hibernate Query.list() to List<Type>?

Examples related to string

How to split a string in two and store it in a field String method cannot be found in a main class method Kotlin - How to correctly concatenate a String Replacing a character from a certain index Remove quotes from String in Python Detect whether a Python string is a number or a letter How does String substring work in Swift How does String.Index work in Swift swift 3.0 Data to String? How to parse JSON string in Typescript