This is a rather simple, but annoying problem I am facing.
There are many places in my application that can use either one or many strings... so to say. I have used a List of string by default.
But every time I have a single string, I am doing this:
List<string> myList = new List<string>();
myList.Add(myString);
A simple myString.ToList()
does not work since it converts into a list of characters and not a list with one string.
Is there an efficient one line way to do this?
How to Convert a String to a List of Words. Another way to convert a string to a list is by using the split() Python method. The split() method splits a string into a list, where each list item is each word that makes up the string. Each word will be an individual list item.
Strings can be converted to lists using list() .
To convert a delimited string to a sequence of strings in C#, you can use the String. Split() method. Since the Split() method returns a string array, you can convert it into a List using the ToList() method.
Using collection initializer:
List<string> myList = new List<string>{myString};
Update. Or, as suggested in comments,
var myList = new List<string>{myString};
I don't at all think that it's worth doing the following, BUT if you really are often creating string lists from single strings, and you really really want the shortest syntax possible - then you could write an extension method:
public static class StringExt
{
public static List<string> AsList(this string self)
{
return new List<string> { self };
}
}
Then you would just do:
var list = myString.AsList();
But like I said, it seems hardly worth it. It also may be confusable with:
var list = myString.ToList();
which (by using Linq) will create a list of chars from the chars in the string.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With