有一个整齐的LINQ的方式来'联盟'一个项目? [英] Is there a neater linq way to 'Union' a single item?
本文介绍了有一个整齐的LINQ的方式来'联盟'一个项目?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如果我有两个序列,我要处理他们两个在一起,我可以联合他们,我们就走了。
If I have two sequences and I want to process them both together, I can union them and away we go.
现在可以说我有我想两者之间sequencs处理一个项目。我可以通过创建一个单一的项目数组得到它,但有一个更合适的方法? 。即
Now lets say I have a single item I want to process between the two sequencs. I can get it in by creating an array with a single item, but is there a neater way? i.e.
var top = new string[] { "Crusty bread", "Mayonnaise" };
string filling = "BTL";
var bottom = new string[] { "Mayonnaise", "Crusty bread" };
// Will not compile, filling is a string, therefore is not Enumerable
//var sandwich = top.Union(filling).Union(bottom);
// Compiles and works, but feels grungy (looks like it might be smelly)
var sandwich = top.Union(new string[]{filling}).Union(bottom);
foreach (var item in sandwich)
Process(item);
是这样做有一个批准的方式,或者是这个批准方法是什么?
Is there an approved way of doing this, or is this the approved way?
感谢
推荐答案
一种选择是自己超负荷
public static IEnumerable<T> Union<T>(this IEnumerable<T> source, T item)
{
return source.Union(Enumerable.Repeat(item, 1));
}
这就是我们所做的与的 的毗连
中的 moreLINQ 。
That's what we did with Concat
in MoreLINQ.
这篇关于有一个整齐的LINQ的方式来'联盟'一个项目?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文