7

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?

2 Answers 2

20

Using collection initializer:

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

Update. Or, as suggested in comments,

var myList = new List<string>{myString};
Sign up to request clarification or add additional context in comments.

4 Comments

Thanks! Saves close to 20 lines!
or even better var myList = new List<string>{myString};
You could wrap this in a method or extension method to make it even more succinct: mystring.ToList()...
@JeffRSon, ok, it's subjective, but I like it more. For me it's even more readable - you see var, you know that your type is taken from right part of expression, and you don't repeating yourself
4

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.

1 Comment

I was just writing the same answer, but you came first ... I considered making it more general, public static List<T> ToSingletonList<T>(this T value) { return new List<T> { value }; } but of course that's not useful if he only needs this for string.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.