有没有一种语句可以在 IEnumerable<T> 中添加一个元素 T?

25
例如:
string element = 'a';
IEnumerable<string> list = new List<string>{ 'b', 'c', 'd' };

IEnumerable<string> singleList = ???; //singleList yields 'a', 'b', 'c', 'd' 

3
在.NET Core中,它是内置的:public static System.Collections.Generic.IEnumerable<TSource> Prepend<TSource> (this System.Collections.Generic.IEnumerable<TSource> source, TSource element); (https://learn.microsoft.com/en-us/dotnet/api/system.linq.enumerable.prepend?view=netcore-2.0) - Niklas Peter
2
作为实现 .Net Standard 2.0 的一部分,它已经包含在 .Net 4.7.1中。 - NetMage
11个回答

0

看了一些例子后,我认为我更喜欢将扩展应用于对象并进行反转。

public static IEnumerable<T> PrependTo<T>(this T value, IEnumerable<T> values) {
    return new[] { value }.Concat(values);
}

用法如下

var singleList = element.PrependTo(list);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接