Thursday, April 21, 2011

Favorite way to create an new IEnumerable<T> sequence from a single value?

I usually create a sequence from a single value using array syntax, like this:

IEnumerable<string> sequence = new string[] { "abc" };

Or using a new List. I'd like to hear if anyone has a more expressive way to do the same thing.

From stackoverflow
  • Your example is not an empty sequence, it's a sequence with one element. To create an empty sequence of strings you can do

    var sequence = Enumerable.Empty<string>();
    

    EDIT OP clarified they were looking to create a single value. In that case

    var sequence = Enumerable.Repeat("abc",1);
    
    Marcel Lamothe : D'oh, I got distracted, sorry. I meant create from an single value, not create an empty instance!
    n8wrl : This is 'the answer' flag it?
  • I like what you suggest, but with the array type omitted:

    var sequence = new[] { "abc" };
    
    Marcel Lamothe : I never realized that you could do that. I think this is clearer than using Repeat.
    Bryan Watts : Yay type inference.

0 comments:

Post a Comment