Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Linq to filter out certain Keys from a Dictionary and return a new dictionary

Tags:

c#

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"

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.

Thanks for your help

like image 303
RamGopal Avatar asked Dec 07 '22 14:12

RamGopal


1 Answers

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);
like image 134
Sergey Kalinichenko Avatar answered Dec 09 '22 02:12

Sergey Kalinichenko