2011-02-09 101 views
2

在C#中,如何使用LINQ過濾SortedDictionary生成也是SortedDictionary的子集?例如。我想寫將SortedDictionary的子集作爲SortedDictionary使用

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

我發現的唯一的方法是創建一個輔助方法和使用

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

如果你想要一個語句的解決方案,這將工作:

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

然而,這是低效率的,因爲它產生兩個字典對象(ToDictionary()擴展方法創建一個,然後將其傳遞給SortedDictionary構造函數)。

你的幫助方法將會帶來更好的性能。爲了更清晰的語法,你可以把它放在了IEnumerable < KeyValuePair < TKEY的擴展方法,TValue > >:

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; 
    } 
} 

它可以這樣使用:

var f2 = source.Where(x => x.Value.foo == bar).ToSortedDictionary();