tags:

views:

26

answers:

1

Hi there. Imagine you would want to select all elements of one sequence all, except elements contained in sequence exceptions and single element otherException.

Is there some better way to do this than? I'd like to avoid creating new array, but I couldn't find a method on the sequence that concats it with a single element.

all.Except(exceptions.Concat(new int[] { otherException }));

complete source code for completeness' sake:

var all = Enumerable.Range(1, 5);
int[] exceptions = { 1, 3 };
int otherException = 2;
var result = all.Except(exceptions.Concat(new int[] { otherException }));
+2  A: 

An alternative (perhaps more readable) would be:

all.Except(exceptions).Except(new int[] { otherException });

You can also create an extension method that converts any object to an IEnumerable, thus making the code even more readable:

public static IEnumerable<T> ToEnumerable<T>(this T item)
{
    return new T[] { item };
}

all.Except(exceptions).Except(otherException.ToEnumerable());

Or if you really want a reusable way to easily get a collection plus one item:

public static IEnumerable<T> Plus<T>(this IEnumerable<T> collection, T item)
{
    return collection.Concat(new T[] { item });
}

all.Except(exceptions.Plus(otherException))
Konamiman
yes, extension methods would be the better way to go.
Axarydax