Linq查询字典,其中值在列表中 [英] Linq Query Dictionary where value in List

查看:321
本文介绍了Linq查询字典,其中值在列表中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Dictionary<string, string>和另一个List<string>.我要实现的是一个linq查询,以使所有项目都脱离字典,其中来自所述字典的任何值都在List<string>中.

I have a Dictionary<string, string> and another List<string>. What I am trying to achieve is a linq query to get all items out of the dictionary where any values from said dictionary are in the List<string>.

我发现这篇文章很有帮助, LINQ针对列表查询字典.并能够编写以下linq表达式,但是我的结果实际上从未返回任何内容.

I found this post to be helpful, LINQ querying a Dictionary against a List . And was able to write the following linq expression, however my results never actually return anything.

到目前为止我所拥有的.

What I have so far.

Data是字典,PersonList是字符串列表.

Data is the dictionary and PersonList is the list of strings.

var Persons = PersonList.Where(x => Data.ContainsKey(x))
                        .Select(z => new { key = z, value = Data[z] })
                        .ToList();

推荐答案

您是否在寻找?如果您要查找,请使用

Are you looking for keys or values? If you're looking for values use

var Persons = Data.Where(kvp => PersonList.Contains(kvp.Value))
                  .ToDictionary(kvp => kvp.Key, kvp => kvp.Value);

如果您确实想要,那么您的代码应该可以使用,但是另一种选择是:

If instead you really want keys then your code should work but another option would be:

var Persons = Data.Where(kvp => PersonList.Contains(kvp.Key))
                  .ToDictionary(kvp => kvp.Key, kvp => kvp.Value);

这篇关于Linq查询字典,其中值在列表中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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