使用Linq从Dictionary中过滤掉某些键并返回一个新词典

Ram*_*pal 4 c# linq

我试图找出一个linq查询,它将从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"};
Run Code Online (Sandbox Code Playgroud)

新词典应仅包含以下条目

"Key2", "Value2"
"Key4", "Value4"
"Key5", "Value5"
Run Code Online (Sandbox Code Playgroud)

我不想制作原始字典的副本并做Dictionary.move,我在想可能有效而且有效.

谢谢你的帮助

das*_*ght 10

您可以过滤原始字典,并ToDictionary在结果上使用:

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