2011-02-09 97 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();