kittikun
kittikun

Reputation: 1909

Finding all values in a Dictionary<string, object> where key contains substring

Let's say I have a dictionary declared as follow:

Dictionary<string, IData> map;

I want to get all the values with the keys containing a specific substring with for example a function like

public IEnumerable<IData> GetContains(string pattern) {}

And I figured how to obtain a list of keys matching the pattern using

var result = mapData.Keys.Where(a => a.Contains(pattern)).ToArray()

but I cannot figure out how to reuse the returned keys to get all the corresponding values in one query.

Upvotes: 4

Views: 6141

Answers (2)

Selman Gen&#231;
Selman Gen&#231;

Reputation: 101681

You can use Where on your Dictionary instead of the Keys collection then get the values with Select:

mapData.Where(kvp => kvp.Key.Contains(pattern)).Select(kvp => kvp.Value);

Upvotes: 13

MarcoLaser
MarcoLaser

Reputation: 266

I think this should work

var result = mapData.Where(entry => entry.Key.Contains(pattern))
                    .Select(item => item.Value);

Upvotes: 2

Related Questions