'Filter Dictionnary<string,string> that do not have their keys in an array string[] [duplicate]
I have the following objects:
IDictionary<string, string> foo = new Dictionary<string, string>() {
{ "key1", "somerandomvalue" },
{ "key2", "somerandomvalue" },
{ "key3", "somerandomvalue" },
{ "key4", "somerandomvalue" }
}
public static readonly string[] bar = {
"key1",
"key3"
};
I would like to filter the Dictionary foo and keep the item that have their keys in the Array bar. So we'll have something like that:
bar: {
{ "key1", "somerandomvalue" },
{ "key3", "somerandomvalue" }
}
I have tried the following but dont understand why the k variable is flagged as char type
foo
.Where(k => x.Key.Any(x => bar.Contains(x.ToString())))
.ToDictionary(k => k.Key, v => v.Value);
Solution 1:[1]
You use need to use Any in Where function by your key collection bar.
foo.Where(x=> bar.Any(b => b == x.Key)).ToDictionary(k => k.Key, v => v.Value);
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | D-Shih |
