开发者

Convert string to List<string> in one line?

开发者 https://www.devze.com 2023-02-10 13:23 出处:网络
I have a string: var names = \"Brian,Jo开发者_StackOverflowe,Chris\"; Is there a way to convert this to a List<string> delimited by , in one line?List<string> result = names.Split(new c

I have a string:

var names = "Brian,Jo开发者_StackOverflowe,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>();


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://learn.microsoft.com/en-us/dotnet/api/system.string.split?view=netframework-4.8


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


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


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

精彩评论

暂无评论...
验证码 换一张
取 消