Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a neater linq way to 'Union' a single item?

Tags:

c#

linq

union

If I have two sequences and I want to process them both together, I can union them and away we go.

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?

Thanks

like image 802
Binary Worrier Avatar asked Aug 20 '10 15:08

Binary Worrier


1 Answers

One option is to overload it yourself:

public static IEnumerable<T> Union<T>(this IEnumerable<T> source, T item) {     return source.Union(Enumerable.Repeat(item, 1)); } 

That's what we did with Concat in MoreLINQ.

like image 73
Jon Skeet Avatar answered Sep 22 '22 15:09

Jon Skeet