tags:

views:

90

answers:

2

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

+9  A: 

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.

Jon Skeet
Enumerable.Repeat, perfect, thanks. I might indeed use that overload, thanks.
Binary Worrier
For extra nerdiness, name the overload `cons` :D
Marc Bollinger
Every so often, when writing C# code, I do find myself longing for the set operation operators from languages like F# or LISP. Syntax like `list :: item` or `list1 @ list2` tend to be quite readable, once you're used to them.
LBushkin
A: 

I tend to have the following somewhere in my code:

public static IEnumerable<T> EmitFromEnum(this T item)
{
  yield return item;
}

While it's not as neat to call col.Union(obj.EmitFromEnum()); as col.Union(obj) it does mean that this single extension method covers all other cases I might want such a single-item enumeration.

Jon Hanna