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