2009-12-17 127 views
3

想象一下,除了序列exceptions中包含的元素和单个元素otherException之外,您希望选择一个序列all的所有元素。将单个元素添加到表达式的序列

有没有比这更好的方法?我想避免创建新的数组,但我无法找到序列中的一个方法,它与单个元素连接。

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

完整的源代码的完整性的缘故:

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

回答

3

一种替代(或许更可读的)将是:

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

还可以创建,其将任何对象的扩展方法到IEnumerable,从而使代码更具可读性:

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

是,扩展方法将是更好的方式去。 – Axarydax 2009-12-17 11:30:56