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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With