0

I have a Dictionary<string, string> in which I am storing paths to my configuration files like:

Config0, <some path>
Config1, <some path>
Config2, <some path>
Someconfigkey, <some path>
Someconfigkey, <some path>
Someconfigkey, <some path>
...
...

I want to get all the key,values from this dictionary for keys that contain substring Config

Any recommendations how to do this efficiently?

Monku
  • 2,440
  • 4
  • 33
  • 57
  • 2
    What do you mean “efficiently”? There nothing better than O(n) here... – Alexei Levenkov Mar 01 '19 at 18:16
  • Remember, a `Dictionary` implements the `IEnumerable>` interface. Which means there is nothing stopping you from using Linq methods to find/select/filter key-value-pairs based on whatever predicate you provide... –  Mar 01 '19 at 18:16
  • It feels like there may be a better starting point. Redesign the data structures perhaps? Also, what is the size of the problem: perhaps O(n) would be efficient enough. – Peter Smith Mar 01 '19 at 18:20
  • How is this a duplicate of the question linked here ?! I am asking for (Key,Value) from the keys that contains a substring provided. The linked 'duplicate' is NOT the SAME! – Monku Mar 01 '19 at 18:26
  • @Monku it's the same principle - you have to loop through the keys (or use a Linq query which loops for you). – D Stanley Mar 01 '19 at 20:08

2 Answers2

1

Since the keys are hashed by their value, if you're not searching for exact key values you'll need to loop through the whole collection of key/value pairs:

foreach (var kvp in dict)
{
    if(kvp.Key.Contains(term))
    {
        // do something
    }
}

You could convert this to a Linq query with Where, but from an efficiency standpoint it's no better than a loop.

If you consistently search for the substring Config, then you could try using two dictionaries: a "config" dictionary and a "non-config" dictionary. It would still be O(n) to loop through each of them but you'd only be looping through the entries that you know contain the substring (your "n" will be smaller).

D Stanley
  • 149,601
  • 11
  • 178
  • 240
0

The following code exempt will create a new dictionary based on another dictionary.

Dictionary<string, string> dict = new Dictionary<string, string>
{
        { "Config0", "0" },
        { "Config1", "1" },
        { "AnotherKey", "2" },
        { "SomeOtherKey", "3" }
};

Dictionary<string, string> configOnlyDictionary = dict.Where(x => x.Key.Contains("Config")).ToDictionary(x => x.Key, x => x.Value);
Devator
  • 3,686
  • 4
  • 33
  • 52