C# 如何尽可能简单地使用 Linq 从字典中选择多个值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12544987/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to select multiple values from a Dictionary using Linq as simple as possible
提问by Peladao
I need to select a number of values (into a List) from a Dictionary based on a subset of keys.
我需要根据键的子集从字典中选择多个值(到列表中)。
I'm trying to do this in a single line of code using Linq but what I have found so far seems quite long and clumsy. What would be the shortest (cleanest) way to do this?
我正在尝试使用 Linq 在一行代码中执行此操作,但到目前为止我发现的内容似乎很长而且很笨拙。执行此操作的最短(最干净)方法是什么?
This is what I have now (the keys are Strings and keysToSelect is a List of keys to select):
这就是我现在所拥有的(键是字符串,keysToSelect 是要选择的键列表):
List<ValueType> selectedValues = dictionary1.Where(x => keysToSelect.Contains(x.Key))
.ToDictionary<String, valueType>(x => x.Key,
x => x.Value)
.Values.ToList;
Thank you.
谢谢你。
采纳答案by verdesmarald
Well you could start from the list instead of the dictionary:
那么你可以从列表而不是字典开始:
var selectedValues = keysToSelect.Where(dictionary1.ContainsKey)
.Select(x => dictionary1[x])
.ToList();
If all the keys are guaranteed to be in the dictionary you can leave out the first Where:
如果保证所有键都在字典中,您可以省略第一个Where:
var selectedValues = keysToSelect.Select(x => dictionary1[x]).ToList();
Note this solution is faster than iterating the dictionary, especially if the list of keys to select is small compared to the size of the dictionary, because Dictionary.ContainsKeyis much faster than List.Contains.
请注意,此解决方案比迭代字典更快,特别是如果要选择的键列表与字典的大小相比较小,因为Dictionary.ContainsKey它比List.Contains.
回答by jeroenh
A Dictionary<TKey,TValue>is IEnumerable<KeyValuePair<TKey,TValue>>, so you can simply Selectthe Valueproperty:
A Dictionary<TKey,TValue>is IEnumerable<KeyValuePair<TKey,TValue>>,因此您可以简单地使用Select该Value属性:
List<ValueType> selectedValues = dictionary1
.Where(x => keysToSelect.Contains(x.Key))
.Select(x => x.Value)
.ToList();
or
或者
var selectValues = (from keyValuePair in dictionary1
where keysToSelect.Contains(keyValuePair.Key)
select keyValuePair.Value).ToList()
回答by Guffa
If you know that all the value that you want to select are in the dictionary, you can loop through the keys instead of looping through the dictionary:
如果您知道要选择的所有值都在字典中,则可以遍历键而不是遍历字典:
List<ValueType> selectedValues = keysToSelect.Select(k => dictionary1[k]).ToList();

