C# 获取SortedDictionary的子集作为SortedDictionary
在C#中,如何使用LINQ过滤SortedDictionary,生成一个子集,该子集也是SortedDictionary?我想写信C# 获取SortedDictionary的子集作为SortedDictionary,c#,linq,C#,Linq,在C#中,如何使用LINQ过滤SortedDictionary,生成一个子集,该子集也是SortedDictionary?我想写信 SortedDictionary<int, Person> source = ..fetch.. SortedDictionary<int, Person> filtered = source.Where(x=>x.foo == bar) SortedDictionary源=…获取。。 SortedDictionary filtere
SortedDictionary<int, Person> source = ..fetch..
SortedDictionary<int, Person> filtered = source.Where(x=>x.foo == bar)
SortedDictionary源=…获取。。
SortedDictionary filtered=source.Where(x=>x.foo==bar)
我找到的唯一方法是创建一个helper方法并使用它
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))
SortedDictionary子词典IEnumerable l)
{
SortedDictionary结果=新的SortedDictionary();
foreach(l中的变量e)
结果[e.键]=e.值;
返回结果;
}
...
SortedDictionary源=…获取。。
SortedDictionary 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));
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();