2009-12-17 62 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