Using Linq to filter specific keys from a dictionary and return a new dictionary

I am trying to figure out a linq query that will filter the list of keys from a Dictionary and return a new filtered 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 contain only the following entries

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

I do not want to make a copy of the original dictionary and do Dictionary.Remove, I think that there may be an effective way than this.

thanks for the help

+4
source share
1 answer

You can filter the source dictionary and use ToDictionary for 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); 
+10
source

Source: https://habr.com/ru/post/1416272/


All Articles