Pel*_*dao 28 c# linq dictionary
我需要根据键的子集从Dictionary中选择一些值(到List中).
我正在尝试使用Linq在一行代码中执行此操作,但到目前为止我发现的内容似乎很长且很笨拙.什么是最短(最干净)的方法呢?
这就是我现在拥有的(键是字符串,keysToSelect是要选择的键列表):
List<ValueType> selectedValues = dictionary1.Where(x => keysToSelect.Contains(x.Key))
.ToDictionary<String, valueType>(x => x.Key,
x => x.Value)
.Values.ToList;
Run Code Online (Sandbox Code Playgroud)
谢谢.
ver*_*ald 59
那么你可以从列表而不是字典开始:
var selectedValues = keysToSelect.Where(dictionary1.ContainsKey)
.Select(x => dictionary1[x])
.ToList();
Run Code Online (Sandbox Code Playgroud)
如果所有的密钥都保证在字典中,你可以省略第一个Where:
var selectedValues = keysToSelect.Select(x => dictionary1[x]).ToList();
Run Code Online (Sandbox Code Playgroud)
请注意,此解决方案比迭代字典更快,特别是如果要选择的键列表与字典的大小相比较小,因为Dictionary.ContainsKey要快得多List.Contains.
一个Dictionary<TKey,TValue>是IEnumerable<KeyValuePair<TKey,TValue>>,这样你就可以简单Select的Value属性:
List<ValueType> selectedValues = dictionary1
.Where(x => keysToSelect.Contains(x.Key))
.Select(x => x.Value)
.ToList();
Run Code Online (Sandbox Code Playgroud)
要么
var selectValues = (from keyValuePair in dictionary1
where keysToSelect.Contains(keyValuePair.Key)
select keyValuePair.Value).ToList()
Run Code Online (Sandbox Code Playgroud)