在C#中,如何使用LINQ对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))发布于 2011-02-09 09:22:20
如果您想要一个单语句解决方案,这将有效:
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>上的扩展方法:
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();https://stackoverflow.com/questions/4942827
复制相似问题