Add one element to the sequence for expression

Imagine that you want to select all the elements in one sequence all, with the exception of the elements contained in the sequence exceptionsand one element otherException.

Is there a better way to do this than? I would like to avoid creating a new array, but I could not find the method in the sequence that combines it with one element.

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

full source code for completeness:

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

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 IEnumerable, which makes the code even more readable:

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

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

:

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

all.Except(exceptions.Plus(otherException))
+3

Source: https://habr.com/ru/post/1725937/