[c#] Shortcut for creating single item list in C#

In C#, is there an inline shortcut to instantiate a List<T> with only one item.

I'm currently doing:

new List<string>( new string[] { "title" } ))

Having this code everywhere reduces readability. I've thought of using a utility method like this:

public static List<T> SingleItemList<T>( T value )
{
    return (new List<T>( new T[] { value } ));
}

So I could do:

SingleItemList("title");

Is there a shorter / cleaner way?

Thanks.

This question is related to c#

The answer is


Michael's idea of using extension methods leads to something even simpler:

public static List<T> InList<T>(this T item)
{
    return new List<T> { item };
}

So you could do this:

List<string> foo = "Hello".InList();

I'm not sure whether I like it or not, mind you...


I would just do

var list = new List<string> { "hello" };

Yet another way, found on "C#/.Net Little wonders" (unfortunately, the site doesn't exist anymore):

Enumerable.Repeat("value",1).ToList()

var list = new List<string>(1) { "hello" };

Very similar to what others have posted, except that it makes sure to only allocate space for the single item initially.

Of course, if you know you'll be adding a bunch of stuff later it may not be a good idea, but still worth mentioning once.


Michael's idea of using extension methods leads to something even simpler:

public static List<T> InList<T>(this T item)
{
    return new List<T> { item };
}

So you could do this:

List<string> foo = "Hello".InList();

I'm not sure whether I like it or not, mind you...


Yet another way, found on "C#/.Net Little wonders" (unfortunately, the site doesn't exist anymore):

Enumerable.Repeat("value",1).ToList()

I would just do

var list = new List<string> { "hello" };

I've got this little function:

public static class CoreUtil
{    
    public static IEnumerable<T> ToEnumerable<T>(params T[] items)
    {
        return items;
    }
}

Since it doesn't prescribe a concrete return type this is so generic that I use it all over the place. Your code would look like

CoreUtil.ToEnumerable("title").ToList();

But of course it also allows

CoreUtil.ToEnumerable("title1", "title2", "title3").ToArray();

I often use it in when I have to append/prepend one item to the output of a LINQ statement. For instance to add a blank item to a selection list:

CoreUtil.ToEnumerable("").Concat(context.TrialTypes.Select(t => t.Name))

Saves a few ToList() and Add statements.

(Late answer, but I stumbled upon this oldie and thought this could be helpful)


You can also do

new List<string>() { "string here" };

Try var

var s = new List<string> { "a", "bk", "ca", "d" };

A different answer to my earlier one, based on exposure to the Google Java Collections:

public static class Lists
{
    public static List<T> Of<T>(T item)
    {
        return new List<T> { item };
    }
}

Then:

List<string> x = Lists.Of("Hello");

I advise checking out the GJC - it's got lots of interesting stuff in. (Personally I'd ignore the "alpha" tag - it's only the open source version which is "alpha" and it's based on a very stable and heavily used internal API.)


I've got this little function:

public static class CoreUtil
{    
    public static IEnumerable<T> ToEnumerable<T>(params T[] items)
    {
        return items;
    }
}

Since it doesn't prescribe a concrete return type this is so generic that I use it all over the place. Your code would look like

CoreUtil.ToEnumerable("title").ToList();

But of course it also allows

CoreUtil.ToEnumerable("title1", "title2", "title3").ToArray();

I often use it in when I have to append/prepend one item to the output of a LINQ statement. For instance to add a blank item to a selection list:

CoreUtil.ToEnumerable("").Concat(context.TrialTypes.Select(t => t.Name))

Saves a few ToList() and Add statements.

(Late answer, but I stumbled upon this oldie and thought this could be helpful)


For a single item enumerable in java it would be Collections.singleton("string");

In c# this is going to be more efficient than a new List:

public class SingleEnumerator<T> : IEnumerable<T>
{
    private readonly T m_Value;

    public SingleEnumerator(T value)
    {
        m_Value = value;
    }

    public IEnumerator<T> GetEnumerator()
    {
        yield return m_Value;
    }

    IEnumerator IEnumerable.GetEnumerator()
    {
        yield return m_Value;
    }
}

but is there a simpler way using the framework?


Michael's idea of using extension methods leads to something even simpler:

public static List<T> InList<T>(this T item)
{
    return new List<T> { item };
}

So you could do this:

List<string> foo = "Hello".InList();

I'm not sure whether I like it or not, mind you...


You can also do

new List<string>() { "string here" };

A different answer to my earlier one, based on exposure to the Google Java Collections:

public static class Lists
{
    public static List<T> Of<T>(T item)
    {
        return new List<T> { item };
    }
}

Then:

List<string> x = Lists.Of("Hello");

I advise checking out the GJC - it's got lots of interesting stuff in. (Personally I'd ignore the "alpha" tag - it's only the open source version which is "alpha" and it's based on a very stable and heavily used internal API.)


Try var

var s = new List<string> { "a", "bk", "ca", "d" };

Use an extension method with method chaining.

public static List<T> WithItems(this List<T> list, params T[] items)
{
    list.AddRange(items);
    return list;
}

This would let you do this:

List<string> strings = new List<string>().WithItems("Yes");

or

List<string> strings = new List<string>().WithItems("Yes", "No", "Maybe So");

Update

You can now use list initializers:

var strings = new List<string> { "This", "That", "The Other" };

See http://msdn.microsoft.com/en-us/library/bb384062(v=vs.90).aspx


I would just do

var list = new List<string> { "hello" };

Use an extension method with method chaining.

public static List<T> WithItems(this List<T> list, params T[] items)
{
    list.AddRange(items);
    return list;
}

This would let you do this:

List<string> strings = new List<string>().WithItems("Yes");

or

List<string> strings = new List<string>().WithItems("Yes", "No", "Maybe So");

Update

You can now use list initializers:

var strings = new List<string> { "This", "That", "The Other" };

See http://msdn.microsoft.com/en-us/library/bb384062(v=vs.90).aspx


You can also do

new List<string>() { "string here" };

A different answer to my earlier one, based on exposure to the Google Java Collections:

public static class Lists
{
    public static List<T> Of<T>(T item)
    {
        return new List<T> { item };
    }
}

Then:

List<string> x = Lists.Of("Hello");

I advise checking out the GJC - it's got lots of interesting stuff in. (Personally I'd ignore the "alpha" tag - it's only the open source version which is "alpha" and it's based on a very stable and heavily used internal API.)


Use an extension method with method chaining.

public static List<T> WithItems(this List<T> list, params T[] items)
{
    list.AddRange(items);
    return list;
}

This would let you do this:

List<string> strings = new List<string>().WithItems("Yes");

or

List<string> strings = new List<string>().WithItems("Yes", "No", "Maybe So");

Update

You can now use list initializers:

var strings = new List<string> { "This", "That", "The Other" };

See http://msdn.microsoft.com/en-us/library/bb384062(v=vs.90).aspx


I would just do

var list = new List<string> { "hello" };

Use an extension method with method chaining.

public static List<T> WithItems(this List<T> list, params T[] items)
{
    list.AddRange(items);
    return list;
}

This would let you do this:

List<string> strings = new List<string>().WithItems("Yes");

or

List<string> strings = new List<string>().WithItems("Yes", "No", "Maybe So");

Update

You can now use list initializers:

var strings = new List<string> { "This", "That", "The Other" };

See http://msdn.microsoft.com/en-us/library/bb384062(v=vs.90).aspx


A different answer to my earlier one, based on exposure to the Google Java Collections:

public static class Lists
{
    public static List<T> Of<T>(T item)
    {
        return new List<T> { item };
    }
}

Then:

List<string> x = Lists.Of("Hello");

I advise checking out the GJC - it's got lots of interesting stuff in. (Personally I'd ignore the "alpha" tag - it's only the open source version which is "alpha" and it's based on a very stable and heavily used internal API.)


Michael's idea of using extension methods leads to something even simpler:

public static List<T> InList<T>(this T item)
{
    return new List<T> { item };
}

So you could do this:

List<string> foo = "Hello".InList();

I'm not sure whether I like it or not, mind you...


new[] { "item" }.ToList();

It's shorter than

new List<string> { "item" };

and you don't have to specify the type.


Inspired by the other answers (and so I can pick it up whenever I need it!), but with naming/style aligned with F# (which has a standard singleton function per data structure*):

namespace System.Collections.Generic
{
    public static class List
    {
        public static List<T> Singleton<T>(T value) => new List<T>(1) { value };
    }
}

* except for ResizeArray itself of course, hence this question :)


In practice I actually name it Create to align with other helpers I define such as Tuple.Create, Lazy.Create[2], LazyTask.Create etc:

namespace System.Collections.Generic
{
    public static class List
    {
        public static List<T> Create<T>(T value) => new List<T>(1) { value };
    }
}

[2]

namespace System
{
    public static class Lazy
    {
        public static Lazy<T> Create<T>(Func<T> factory) => new Lazy<T>(factory);
    }
}

You can also do

new List<string>() { "string here" };

new[] { "item" }.ToList();

It's shorter than

new List<string> { "item" };

and you don't have to specify the type.


var list = new List<string>(1) { "hello" };

Very similar to what others have posted, except that it makes sure to only allocate space for the single item initially.

Of course, if you know you'll be adding a bunch of stuff later it may not be a good idea, but still worth mentioning once.


Inspired by the other answers (and so I can pick it up whenever I need it!), but with naming/style aligned with F# (which has a standard singleton function per data structure*):

namespace System.Collections.Generic
{
    public static class List
    {
        public static List<T> Singleton<T>(T value) => new List<T>(1) { value };
    }
}

* except for ResizeArray itself of course, hence this question :)


In practice I actually name it Create to align with other helpers I define such as Tuple.Create, Lazy.Create[2], LazyTask.Create etc:

namespace System.Collections.Generic
{
    public static class List
    {
        public static List<T> Create<T>(T value) => new List<T>(1) { value };
    }
}

[2]

namespace System
{
    public static class Lazy
    {
        public static Lazy<T> Create<T>(Func<T> factory) => new Lazy<T>(factory);
    }
}

For a single item enumerable in java it would be Collections.singleton("string");

In c# this is going to be more efficient than a new List:

public class SingleEnumerator<T> : IEnumerable<T>
{
    private readonly T m_Value;

    public SingleEnumerator(T value)
    {
        m_Value = value;
    }

    public IEnumerator<T> GetEnumerator()
    {
        yield return m_Value;
    }

    IEnumerator IEnumerable.GetEnumerator()
    {
        yield return m_Value;
    }
}

but is there a simpler way using the framework?


var list = new List<string>(1) { "hello" };

Very similar to what others have posted, except that it makes sure to only allocate space for the single item initially.

Of course, if you know you'll be adding a bunch of stuff later it may not be a good idea, but still worth mentioning once.