开发者

Add single element to a sequence for an expression

开发者 https://www.devze.com 2022-12-14 10:32 出处:网络
Imagine you would want to select all elements of one sequence all, except elements contained in sequence exceptions and single element otherException.

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 }));


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))
0

精彩评论

暂无评论...
验证码 换一张
取 消