Valamas
Valamas

Reputation: 24729

Can converting a string to a List<string> be simplified?

For ease of passing a parameter, I am converting a string to a List.

This is my working example

string single = "single";

List<string> list = (new [] {single}).ToList();

Can this be shortened?

This attempt is incorrect as the list becomes a list of char.

List<char> wronglist = single.ToList();

Upvotes: 2

Views: 663

Answers (3)

Tim S.
Tim S.

Reputation: 56536

You could write an extension method, but I'd choose a name besides ToList to prevent confusion for items that are enumerable themselves (normally, single.ToList() would return a List<char>).

public static IList<T> AsList<T>(this T single) {
    return new List<T> { single };
}

// e.g.
IList<string> myList = single.AsList();

Upvotes: 0

krillgar
krillgar

Reputation: 12805

If you want that syntax, you could create an Extension method.

public static IList<string> ToList(this string) {
    return new List<string>{single};
}

Then you could have this with no problems (if there's a conflict with an existing string.ToList(), you can always rename this extension).

string single = "single";
List<string> list = single.ToList();

Upvotes: 1

Habib
Habib

Reputation: 223267

Simplest would be:

List<string> list = new List<string>{single};

See: Collection Initializer - MSDN

Collection initializers let you specify one or more element initializers when you initialize a collection class that implements IEnumerable.

Upvotes: 10

Related Questions