在 C# 中,如何使用 LINQ 过滤 SortedDictionary 生成一个也是 SortedDictionary 的子集?例如。我想写
SortedDictionary<int, Person> source = ..fetch..
SortedDictionary<int, Person> filtered = source.Where(x=>x.foo == bar)
Run Code Online (Sandbox Code Playgroud)
我发现的唯一方法是创建一个辅助方法并使用它
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))
Run Code Online (Sandbox Code Playgroud)
如果您想要一个单语句解决方案,这将起作用:
SortedDictionary<int, Person> filtered =
new SortedDictionary<int, Person>(
source.Where(x => x.Value.foo == bar)
.ToDictionary(kvp => kvp.Key, kvp => kvp.Value));
Run Code Online (Sandbox Code Playgroud)
但是,它效率低下,因为它创建了两个字典对象(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;
}
}
Run Code Online (Sandbox Code Playgroud)
可以这样使用:
var f2 = source.Where(x => x.Value.foo == bar).ToSortedDictionary();
Run Code Online (Sandbox Code Playgroud)