是否存在将元素T放在IEnumerable T之前的声明. [英] Is there a statement to prepend an element T to a IEnumerable<T>
本文介绍了是否存在将元素T放在IEnumerable T之前的声明.的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
例如:
string element = 'a';
IEnumerable<string> list = new List<string>{ 'b', 'c', 'd' };
IEnumerable<string> singleList = ???; //singleList yields 'a', 'b', 'c', 'd'
推荐答案
我认为您不能只是Insert
进入现有列表吗?
I take it you can't just Insert
into the existing list?
好吧,您可以使用new[] {element}.Concat(list)
.
否则,您可以编写自己的扩展方法:
Otherwise, you could write your own extension method:
public static IEnumerable<T> Prepend<T>(
this IEnumerable<T> values, T value) {
yield return value;
foreach (T item in values) {
yield return item;
}
}
...
var singleList = list.Prepend("a");
这篇关于是否存在将元素T放在IEnumerable T之前的声明.的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文