我有一个 Dictionary<string, List<int>>在我以下列方式使用的代码中:
Key Values
2011-07-15 1, 2, 3
2011-07-20 4, 5, 6
2010-02-11 7, 8, 9
我的代码需要能够查询与键中特定子字符串匹配的所有值。例如,如果我有子字符串 2011-07它应该返回值 {1, 2, 3, 4, 5, 6} . 11 的子串应该从 1-9 返回所有 ID .
任何人都可以推荐一种简洁的方法来实现这一目标吗?或者提供更好的数据结构来检索这些信息?
最佳答案
我会做一个扩展方法:
public static class DictionaryExt
{
public static IEnumerable<T> PartialMatch<T>(this Dictionary<string, T> dictionary, string partialKey)
{
// This, or use a RegEx or whatever.
IEnumerable<string> fullMatchingKeys =
dictionary.Keys.Where(currentKey => currentKey.Contains(partialKey));
List<T> returnedValues = new List<T>();
foreach (string currentKey in fullMatchingKeys)
{
returnedValues.Add(dictionary[currentKey]);
}
return returnedValues;
}
}
向字典添加值的“成本”不会改变,但检索成本会更高,但前提是您知道要进行部分匹配。
顺便说一句,我相信您可以在单个 Lambda 表达式中转换它,但概念保持不变。
编辑:在您的示例中,此方法将返回 2 个值列表,但您可以更改它以合并列表。这是您可以执行的扩展方法:
public static IEnumerable<T> PartialMatch<T>(
this Dictionary<string, IEnumerable<T>> dictionary,
string partialKey)
{
// This, or use a RegEx or whatever.
IEnumerable<string> fullMatchingKeys =
dictionary.Keys.Where(currentKey => currentKey.Contains(partialKey));
List<T> returnedValues = new List<T>();
foreach (string currentKey in fullMatchingKeys)
{
returnedValues.AddRange(dictionary[currentKey]);
}
return returnedValues;
}
编辑 2:想想看,您还可以使其更通用。使用下一个扩展方法,它可以在任何字典上工作,只要你提供一个 comparer 来检查你所说的“部分匹配”是什么意思:
public static IEnumerable<TValue> PartialMatch<TKey, TValue>(
this Dictionary<TKey, IEnumerable<TValue>> dictionary,
TKey partialKey,
Func<TKey, TKey, bool> comparer)
{
// This, or use a RegEx or whatever.
IEnumerable<TKey> fullMatchingKeys =
dictionary.Keys.Where(currentKey => comparer(partialKey, currentKey));
List<TValue> returnedValues = new List<TValue>();
foreach (TKey currentKey in fullMatchingKeys)
{
returnedValues.AddRange(dictionary[currentKey]);
}
return returnedValues;
}
关于c# - 是否可以对字典字符串键进行部分字符串匹配?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7816398/
总的来说,我对ruby还比较陌生,我正在为我正在创建的对象编写一些rspec测试用例。许多测试用例都非常基础,我只是想确保正确填充和返回值。我想知道是否有办法使用循环结构来执行此操作。不必为我要测试的每个方法都设置一个assertEquals。例如:describeitem,"TestingtheItem"doit"willhaveanullvaluetostart"doitem=Item.new#HereIcoulddotheitem.name.shouldbe_nil#thenIcoulddoitem.category.shouldbe_nilendend但我想要一些方法来使用
我有一个字符串input="maybe(thisis|thatwas)some((nice|ugly)(day|night)|(strange(weather|time)))"Ruby中解析该字符串的最佳方法是什么?我的意思是脚本应该能够像这样构建句子:maybethisissomeuglynightmaybethatwassomenicenightmaybethiswassomestrangetime等等,你明白了......我应该一个字符一个字符地读取字符串并构建一个带有堆栈的状态机来存储括号值以供以后计算,还是有更好的方法?也许为此目的准备了一个开箱即用的库?
类classAprivatedeffooputs:fooendpublicdefbarputs:barendprivatedefzimputs:zimendprotecteddefdibputs:dibendendA的实例a=A.new测试a.foorescueputs:faila.barrescueputs:faila.zimrescueputs:faila.dibrescueputs:faila.gazrescueputs:fail测试输出failbarfailfailfail.发送测试[:foo,:bar,:zim,:dib,:gaz].each{|m|a.send(m)resc
很好奇,就使用rubyonrails自动化单元测试而言,你们正在做什么?您是否创建了一个脚本来在cron中运行rake作业并将结果邮寄给您?git中的预提交Hook?只是手动调用?我完全理解测试,但想知道在错误发生之前捕获错误的最佳实践是什么。让我们理所当然地认为测试本身是完美无缺的,并且可以正常工作。下一步是什么以确保他们在正确的时间将可能有害的结果传达给您? 最佳答案 不确定您到底想听什么,但是有几个级别的自动代码库控制:在处理某项功能时,您可以使用类似autotest的内容获得关于哪些有效,哪些无效的即时反馈。要确保您的提
我的目标是转换表单输入,例如“100兆字节”或“1GB”,并将其转换为我可以存储在数据库中的文件大小(以千字节为单位)。目前,我有这个:defquota_convert@regex=/([0-9]+)(.*)s/@sizes=%w{kilobytemegabytegigabyte}m=self.quota.match(@regex)if@sizes.include?m[2]eval("self.quota=#{m[1]}.#{m[2]}")endend这有效,但前提是输入是倍数(“gigabytes”,而不是“gigabyte”)并且由于使用了eval看起来疯狂不安全。所以,功能正常,
在我的Rails(2.3,Ruby1.8.7)应用程序中,我需要将字符串截断到一定长度。该字符串是unicode,在控制台中运行测试时,例如'א'.length,我意识到返回了双倍长度。我想要一个与编码无关的长度,以便对unicode字符串或latin1编码字符串进行相同的截断。我已经了解了Ruby的大部分unicode资料,但仍然有些一头雾水。应该如何解决这个问题? 最佳答案 Rails有一个返回多字节字符的mb_chars方法。试试unicode_string.mb_chars.slice(0,50)
给定这段代码defcreate@upgrades=User.update_all(["role=?","upgraded"],:id=>params[:upgrade])redirect_toadmin_upgrades_path,:notice=>"Successfullyupgradeduser."end我如何在该操作中实际验证它们是否已保存或未重定向到适当的页面和消息? 最佳答案 在Rails3中,update_all不返回任何有意义的信息,除了已更新的记录数(这可能取决于您的DBMS是否返回该信息)。http://ar.ru
在控制台中反复尝试之后,我想到了这种方法,可以按发生日期对类似activerecord的(Mongoid)对象进行分组。我不确定这是完成此任务的最佳方法,但它确实有效。有没有人有更好的建议,或者这是一个很好的方法?#eventsisanarrayofactiverecord-likeobjectsthatincludeatimeattributeevents.map{|event|#converteventsarrayintoanarrayofhasheswiththedayofthemonthandtheevent{:number=>event.time.day,:event=>ev
对于具有离线功能的智能手机应用程序,我正在为Xml文件创建单向文本同步。我希望我的服务器将增量/差异(例如GNU差异补丁)发送到目标设备。这是计划:Time=0Server:hasversion_1ofXmlfile(~800kiB)Client:hasversion_1ofXmlfile(~800kiB)Time=1Server:hasversion_1andversion_2ofXmlfile(each~800kiB)computesdeltaoftheseversions(=patch)(~10kiB)sendspatchtoClient(~10kiBtransferred)Cl
大约一年前,我决定确保每个包含非唯一文本的Flash通知都将从模块中的方法中获取文本。我这样做的最初原因是为了避免一遍又一遍地输入相同的字符串。如果我想更改措辞,我可以在一个地方轻松完成,而且一遍又一遍地重复同一件事而出现拼写错误的可能性也会降低。我最终得到的是这样的:moduleMessagesdefformat_error_messages(errors)errors.map{|attribute,message|"Error:#{attribute.to_s.titleize}#{message}."}enddeferror_message_could_not_find(obje