使用LINQ过滤掉从字典某些键,并返回一个新的字典 [英] Using Linq to filter out certain Keys from a Dictionary and return a new dictionary

查看:204
本文介绍了使用LINQ过滤掉从字典某些键,并返回一个新的字典的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图找出一个LINQ查询,将过滤掉从字典键列表,并返回一个新的过滤掉字典

I am trying to figure out a linq query that will filter out a list of keys from a Dictionary and return a new filtered out dictionary

var allDictEnteries = new Dictionary<string, string>
                                     {
                                         {"Key1", "Value1"},
                                         {"Key2", "Value2"},
                                         {"Key3", "Value3"},
                                         {"Key4", "Value4"},
                                         {"Key5", "Value5"},
                                         {"Key6", "Value6"}
                                     };
var keysToBeFiltered = new List<string> {"Key1", "Key3", "Key6"};

新的字典应该只包含以下条目

The new dictionary should only contain the following entries

"Key2", "Value2"
"Key4", "Value4"
"Key5", "Value5"

我不想让原来的字典的副本,并做Dictionary.Remove,我想有可能是,比有效的方法

I don't want to make a copy of the original dictionary and do Dictionary.Remove, I am thinking there might be and efficient way than that.

您的帮助谢谢

推荐答案

您可以过滤原字典,并使用 ToDictionary 的结果是:

You can filter the original dictionary, and use ToDictionary on the result:

var keysToBeFiltered = new HashSet<string> {"Key1", "Key3", "Key6"};
var filter = allDictEnteries
    .Where(p => !keysToBeFiltered.Contains(p.Key))
    .ToDictionary(p => p.Key, p => p.Value);

这篇关于使用LINQ过滤掉从字典某些键,并返回一个新的字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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