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

C#LinqC# 3.0

C# Problem Overview


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.

C# Solutions


Solution 1 - C#

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);

Solution 2 - C#

I like what you suggest, but with the array type omitted:

var sequence = new[] { "abc" };

Solution 3 - C#

Or even shorter,

string[] single = { "abc" };

I would make an extension method:

public static T[] Yield<T>(this T item)
{
    T[] single = { item };
    return single;
}

Or even better and shorter, just

public static IEnumerable<T> Yield<T>(this T item)
{
    yield return item;
}

Perhaps this is exactly what Enumerable.Repeat is doing under the hood.

Solution 4 - C#

or just create a method

public static IEnumerable<T> CreateEnumerable<T>(params T[] items)
{
    if(items == null)
        yield break;

    foreach (T mitem in items)
        yield return mitem;
}

or

public static IEnumerable<T> CreateEnumerable<T>(params T[] items)
{
   return items ?? Enumerable.Empty<T>();
}

usage :

IEnumerable<string> items = CreateEnumerable("single");

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionMarcel LamotheView Question on Stackoverflow
Solution 1 - C#JaredParView Answer on Stackoverflow
Solution 2 - C#Bryan WattsView Answer on Stackoverflow
Solution 3 - C#nawfalView Answer on Stackoverflow
Solution 4 - C#AndrewView Answer on Stackoverflow