如何使用Linq尽可能简单地从Dictionary中选择多个值 [英] How to select multiple values from a Dictionary using Linq as simple as possible

查看:50
本文介绍了如何使用Linq尽可能简单地从Dictionary中选择多个值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要根据键的子集从词典"中选择多个值(进入列表).

我正在尝试使用Linq在一行代码中执行此操作,但是到目前为止,我发现的内容似乎很长而且很笨拙.最简单(最干净)的方法是什么?

这就是我现在拥有的(键是字符串,keysToSelect是要选择的键的列表):

List<ValueType> selectedValues = dictionary1.Where(x => keysToSelect.Contains(x.Key))
                                            .ToDictionary<String, valueType>(x => x.Key,
                                                                             x => x.Value)
                                            .Values.ToList;

谢谢.

解决方案

好吧,您可以从列表开始而不是从字典开始:

var selectedValues = keysToSelect.Where(dictionary1.ContainsKey)
                     .Select(x => dictionary1[x])
                     .ToList();

如果保证所有键都在字典中,则可以省略第一个Where:

var selectedValues = keysToSelect.Select(x => dictionary1[x]).ToList();

请注意,此解决方案比迭代字典要快,尤其是如果要选择的键列表比字典的大小小时,因为Dictionary.ContainsKeyList.Contains快得多.

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?

This is what I have now (the keys are Strings and keysToSelect is a List of keys to select):

List<ValueType> selectedValues = dictionary1.Where(x => keysToSelect.Contains(x.Key))
                                            .ToDictionary<String, valueType>(x => x.Key,
                                                                             x => x.Value)
                                            .Values.ToList;

Thank you.

解决方案

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:

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.ContainsKey is much faster than List.Contains.

这篇关于如何使用Linq尽可能简单地从Dictionary中选择多个值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆