Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

One line conversion of string to List<string> in C#

Tags:

string

c#

list

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?

like image 943
rtindru Avatar asked Jul 02 '13 07:07

rtindru


People also ask

How do I convert a string to a list of strings?

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.

Can you convert a string to a list?

Strings can be converted to lists using list() .

How can I convert comma separated string into a list string C#?

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.


2 Answers

Using collection initializer:

List<string> myList = new List<string>{myString};

Update. Or, as suggested in comments,

var myList = new List<string>{myString};
like image 172
Andrei Avatar answered Oct 05 '22 05:10

Andrei


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.

like image 45
Matthew Watson Avatar answered Oct 05 '22 03:10

Matthew Watson