dictionary : search key strings with a like feature
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.
You can access the Keys property of the Dictionary and then use a Linq query to evaluate your keys:
var dictionary = new Dictionary<string,string>();
dictionary.Keys.Where( key => key.Contains("a")).ToList();
You can use LINQ
Something like this
myDic.Where(d=>d.Key.StartWith("a")).ToDictionary(d=>d.Key,d=>d.Value)
Or
myDic.Where(d=>d.Key.Contains("b")).ToDictionary(d=>d.Key,d=>d.Value)
Or
myDic.Where(d=>some other condition with d.Key).ToDictionary(d=>d.Key,d=>d.Value)
Just use Linq:
var query = myDict.Where(x => x.Key.IndexOf('a') > -1 && x.Key.IndexOf("d_") == -1);
Here's a little extension I whipped up:
public static IList<string> KeysLikeAt(this Dictionary<string, object> dictionary, char letter, int index)
{
return dictionary.Where(k => k.Key.Length > index && k.Key[index] == letter)
.Select(k => k.Key).ToList();
}
public static IList<string> KeysNotLikeAt(this Dictionary<string, object> dictionary, char letter, int index)
{
return dictionary.Where(k => k.Key.Length > index && k.Key[index] != letter)
.Select(k => k.Key).ToList();
}
and you can use it like so:
IList<string> keysStartingWithA = dictionary.KeysLikeAt('a', 0);
IList<string> keysNotStartingWithD = dictionary.KeysNotLikeAt('d', 0);
精彩评论