从一个值创建一个新的 IEnumable < T > 序列的最喜欢的方法是什么?

我通常使用数组语法从单个值创建序列,如下所示:

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

或者使用新的 List。我想听听是否有人能用更有表现力的方式做同样的事情。

91443 次浏览

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

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

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

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.

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