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 !
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With