2013-03-21 3 views
4

다른 조건으로 필터링하려는 사전이 있습니다.대리인에서 사전을 사용하는 방법

IDictionary<string, string> result = collection.Where(r => r.Value == null).ToDictionary(r => r.Key, r => r.Value); 

I는 예를 들어 실제 필터링을 수행하는 방법에 관한 매개 변수로 Where 절 전달하고자

private static IDictionary<T1, T2> Filter<T1, T2>(Func<IDictionary<T1, T2>, IDictionary<T1, T2>> exp, IDictionary<T1, T2> col) 
{ 
    return col.Where(exp).ToDictionary<T1, T2>(r => r.Key, r => r.Value); 
} 

이것은 컴파일되지 않습니다.

나는 내가 뭘 잘못

Func<IDictionary<string, string>, IDictionary<string, string>> expression = r => r.Value == null; 
var result = Filter<string, string>(expression, collection); 

를 사용하여이 메소드를 호출하는 시도?

+0

@Daniel Hilgarth과 같이

public static class Extensions { public static IDictionairy<TKey, TValue> Filter<TKey, TValue>(this IDictionary<TKey, TValue> source, Func<KeyValuePair<TKey, TValue>, bool> filterDelegate) { return source.Where(filterDelegate).ToDictionary(x => x.Key, x => x.Value); } } 

전화. 그 점을 지적 해 주셔서 감사합니다. – Rotte2

답변

7

WhereFunc<TSource, bool>이 필요합니다. 귀하의 경우는 Func<KeyValuePair<TKey, TValue>, bool>입니다.

또한 메서드의 반환 형식이 잘못되었습니다. string 대신 T1T2을 사용해야합니다. 또한 일반 매개 변수에 설명적인 이름을 사용하는 것이 좋습니다. 당신이 Where 확장 메서드의 생성자를 보면

private static IDictionary<TKey, TValue> Filter<TKey, TValue>(
    Func<KeyValuePair<TKey, TValue>, bool> exp, IDictionary<TKey, TValue> col) 
{ 
    return col.Where(exp).ToDictionary(r => r.Key, r => r.Value); 
} 
+0

'IDictionary 가'IEnumerable > '에서 상속 받기 때문에'Func '가 필요하다는 메모를 추가 할 수 있습니다. 그러나 이미 upvoted :-) – sloth

+0

@DominicKexel : 당신은 그 메모를 직접 추가, 나는 그것이 충분하다고 생각합니다 :) –

+0

@ DanielHilgarth : 고마워. 그것은 매력처럼 작동합니다! – Rotte2

0

당신이 그래서

Func<KeyValuePair<string, string>, bool>

표시됩니다 TKeyTValue - 대신 T1T2의 나는 사전과 같은 이름을 사용 당신이 필터링 해야하는 것입니다,이 확장 방법을 시도하십시오. 반환 형식을 고정 :

IDictionary<string, string> dictionairy = new Dictionary<string, string>(); 
var result = dictionairy.Filter((x => x.Key == "YourValue")); 
+0

그것은 OP가 원하는 것을 실제로하지 않습니다. 당신의'Filter' 메쏘드는 어떤 * 이점도 추가하지 않습니다. OP의'Filter' 메쏘드는 filtered * dictionary *를 반환합니다. –

+0

@DanielHilgarth 좋아요. 결국 ToDictionairy()를 추가 할 것입니다. 문제가 없습니다 : P – LukeHennerley

관련 문제