我有一个 Dictionary<string,int>
其中有一些值。例如:
- “一个”,600
- “b”,550
- “c”, 400
我想过滤此列表以保留大于 500 的值。我不经常使用 C#,也没有使用任何 LINQ。我认为这可能是学习的好时机。所以,我尝试了以下方法:
Dictionary<string,int> someDictionary = new Dictionary();
// Code to populate someDictionary goes here
someDictionary = (Dictionary<string,int>) someDictionary.Where(pair => pair.Value > 500);
这会抛出一个 InvalidCastException:
Unable to cast object of type 'WhereEnumerableIterator`1[System.Collections.Generic.KeyValuePair`2[System.String,System.Int32]]' to type 'System.Collections.Generic.Dictionary`2[System.String,System.Int32]'.
我尝试了一些转换,调用了 .ToDictionary()
等等。我似乎无法弄清楚如何正确地转换它,或者如何正确地使用语法。你能为我指出正确的方向吗?感谢您的宝贵时间。
最佳答案
您需要使用 ToDictionary,然后传递键的选择器,然后传递值的选择器。
someDictionary = someDictionary.Where(pair => pair.Value > 500)
.ToDictionary(p => p.Key, p => p.Value);
关于c# - 使用 LINQ 按值过滤字典时遇到麻烦,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16431625/