Create an enumeration of one

If I want an empty listing, I can call Enumerable.Empty<T>(). But what if I want to convert a scalar type to an enumeration?

I usually write new List<string> {myString}to pass to a myStringfunction that takes IEnumerable<string>. Is there another LINQ-y way?

+5
source share
4 answers

You can use Repeat:

var justOne = Enumerable.Repeat(value, 1);

Or just an array, of course:

var singleElementArray = new[] { value };

Of course, the version of the array is changed, while it is Enumerable.Repeatnot.

+9
source

Exists, but it is less efficient than using a list or array:

// an enumeration containing only the number 13.
var oneIntEnumeration = Enumerable.Repeat(13, 1);
+3
source

,

var sequence = new[] { value };
+3

:

public static class Extensions
{
    public static IEnumerable<T> AsEnumerable<T>(this T item)
    {
         yield return item;
    }
}

, , Enumerable.Repeat, , , ( - ). :

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

And that, of course, works if you call it with one argument. But perhaps within the framework there is already something similar that I have not yet discovered.

+1
source

All Articles