Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

dictionary : search key strings with a like feature

Tags:

c#

dictionary

I want to search my keys in Dictionary with a like feature. I want to takes the keys begin with "a" or their 3rd letter is "e" or their 4rt letter is not "d"

in sql it is possible to write queries " where (key like 'a') and (key not like 'd__') " I want to have this feature for Dictionary . Any algorithm suggestion you have ?

Thanks !

like image 950
softwaremonster Avatar asked Jan 24 '11 19:01

softwaremonster


Video Answer


1 Answers

While this will be the SQL equivalent of a table scan, you can use LINQ or the IEnumerable<T> extension methods to search your dictionary for all values whose keys match a pattern:

Extension Method:

var values = dictionary.Where(pv => 
             pv.Key.StartsWith("A") || 
             (pv.Key.Length >= 3 && pv.Key[2] == 'e') || 
             pv.Key.Length < 4 || 
             pv.Key[3] != 'd').Select(pv => pv.Value);

LINQ:

var values = (from pv in dictionary
              where pv.Key.StartsWith("A") ||
                    (pv.Key.Legnth >= 3 && pv.Key[2] == 'e') ||
                    pv.Length < 4 ||
                    pv.Key[3] != 'd'
                    select pv.Value);

Note that the last part of both of these predicates pertains to your "fourth letter is not "d". I took that to mean that a string that was three characters (or fewer) long would match this. If you mean the string is at least four characters AND its fourth character is not "d", then the changes should be obvious.

Be aware that the primary (performance) benefit to the Dictionary class is using hash-based key lookups, which (in the average and best case) is O(1). Using a linear search like this is O(n), so something like this will, in general, be slower than an ordinary key lookup.

like image 122
Adam Robinson Avatar answered Oct 17 '22 01:10

Adam Robinson