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

Viewed 6904

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

4 Answers

The new way of doing this, supported in .NET Core and .NET Framework from version 4.7.1, is using the Append extension method.

This will make your code as easy and elegant as

var sandwich = top.Append(filling).Union(bottom);
Related