我想用类似的功能在Dictionary中搜索我的键.我想把钥匙以"a"开头或者他们的第3个字母是"e"或者他们的4rt字母不是"d"
在sql中,可以编写查询"where(键类似' a ')和(键不喜欢'd__ ')"我希望将此功能用于Dictionary.您有任何算法建议吗?
谢谢 !
bry*_*ook 13
您可以访问Dictionary的Keys属性,然后使用Linq查询来评估您的键:
var dictionary = new Dictionary<string,string>();
dictionary.Keys.Where( key => key.Contains("a")).ToList();
Run Code Online (Sandbox Code Playgroud)
Ada*_*son 13
虽然这将是SQL扫描的等价物,但您可以使用LINQ或IEnumerable<T>扩展方法在字典中搜索其键与模式匹配的所有值:
扩展方法:
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);
Run Code Online (Sandbox Code Playgroud)
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);
Run Code Online (Sandbox Code Playgroud)
请注意,这两个谓词的最后一部分都与你的"第四个字母不是"d"有关.我认为这意味着长度为三个字符(或更少)的字符串会与此匹配.如果你的意思是字符串是至少四个字符和它的第四个字符不是"d",那么变化应该是显而易见的.
请注意,Dictionary该类的主要(性能)优势是使用基于散列的键查找,(在平均和最好的情况下)是O(1).使用像这样的线性搜索是O(n),所以这样的东西通常比普通的密钥查找慢.
您可以使用 LINQ
像这样的东西
myDic.Where(d=>d.Key.StartWith("a")).ToDictionary(d=>d.Key,d=>d.Value)
Run Code Online (Sandbox Code Playgroud)
或者
myDic.Where(d=>d.Key.Contains("b")).ToDictionary(d=>d.Key,d=>d.Value)
Run Code Online (Sandbox Code Playgroud)
或者
myDic.Where(d=>some other condition with d.Key).ToDictionary(d=>d.Key,d=>d.Value)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
31144 次 |
| 最近记录: |