Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/283.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 获取SortedDictionary的子集作为SortedDictionary_C#_Linq - Fatal编程技术网

C# 获取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

在C#中,如何使用LINQ过滤SortedDictionary,生成一个子集,该子集也是SortedDictionary?我想写信

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();