2011-02-09 10 views
2

C#では、SortedDictionaryであるサブセットを生成するLINQを使用してSortedDictionaryをフィルタする方法を教えてください。例えば。私は私が見つけた唯一の方法はSortedDictionaryのサブセットをSortedDictionaryとして取得する

SortedDictionary<TKey, TValue> SubDictionary<TKey, TValue> IEnumerable<KeyValuePair<TKey, TValue>> l) 
{ 
    SortedDictionary<TKey, TValue> result = new SortedDictionary<TKey, TValue>(); 
    foreach (var e in l) 
     result[e.Key] = e.Value; 
    return result; 
} 

... 

SortedDictionary<int, Person> source = ..fetch.. 
SortedDictionary<int, Person> filtered = SubDictionary(source.Where(x=>x.foo == bar)) 

答えて

4

を使用すると、1つの文のソリューションが必要な場合というヘルパーメソッドを作成して使用することである

SortedDictionary<int, Person> source = ..fetch.. 
SortedDictionary<int, Person> filtered = source.Where(x=>x.foo == bar) 

書きたいのですが、この意志仕事:

SortedDictionary<int, Person> filtered = 
    new SortedDictionary<int, Person>(
     source.Where(x => x.Value.foo == bar) 
       .ToDictionary(kvp => kvp.Key, kvp => kvp.Value)); 

しかし、ToDictionary()拡張メソッドは2つの辞書オブジェクトを作成するため、非効率的ですSortedDictionaryコンストラクタに渡されます)。

あなたのヘルパー方法は、より良いパフォーマンスをもたらします。クリーナー構文については、あなたは、それIEnumerableを< KeyValuePair <処理鍵の拡張メソッドTValue > >を作ることができる:

var f2 = source.Where(x => x.Value.foo == bar).ToSortedDictionary(); 
:このように使用することができます

public static class KeyValuePairEnumerableExtensions 
{ 
    public static SortedDictionary<TKey, TValue> ToSortedDictionary<TKey, TValue>(
     this IEnumerable<KeyValuePair<TKey, TValue>> l) 
    { 
     SortedDictionary<TKey, TValue> result = new SortedDictionary<TKey, TValue>(); 
     foreach (var e in l) 
      result[e.Key] = e.Value; 
     return result; 
    } 
} 

関連する問題