C# 从单个值创建新 IEnumerable<T> 序列的最喜欢的方法?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1019737/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 05:41:22  来源:igfitidea点击:

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

c#linqc#-3.0

提问by Marcel Lamothe

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.

或使用新列表。我想听听是否有人有一种更有表现力的方式来做同样的事情。

采纳答案by JaredPar

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

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

编辑OP 澄清他们希望创造一个单一的价值。在这种情况下

var sequence = Enumerable.Repeat("abc",1);

回答by Bryan Watts

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

我喜欢你的建议,但省略了数组类型:

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

回答by nawfal

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.Repeatis doing under the hood.

也许这正是幕后所做Enumerable.Repeat的事情。

回答by Andrew

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