【发布时间】:2013-10-31 23:33:50
【问题描述】:
我正在遍历字符串列表以查看该字符串是否包含在字典的值中,然后尝试从值中删除该字符串。
目前我是这样做的:
Dictionary<String, String> formValues = new Dictionary<String, String>();
formValues["key1"] = "the something at";
formValues["key2"] = "the something on";
formValues["key3"] = "the something is";
string prepositionList = "at,as,if,of,the,to,a,an,it,is,by,its";
List<string> prepositionListValues = new List<string>(prepositionList.Split(','));
foreach (string preposition in prepositionListValues)
{
List<string> keys = new List<string>(formValues.Keys);
foreach (string key in keys)
{
if (formValues[key] != null)
{
if (formValues[key].Contains(preposition))
{
formValues[key] = formValues[key].Replace(preposition, "");
}
}
}
}
对我来说,这似乎有点啰嗦。有没有“更好”的方式来做到这一点?
【问题讨论】:
-
为什么我的问题被否决了?
-
如果字典很大,那么这是非常低效的;请记住,字典旨在快速查找与给定键关联的值,而不是快速查找给定值!如果这是一个你必须做很多的操作,那么你应该有两个字典;一个常规的“正向”字典,然后是一个从值映射回关联键序列的“反向”字典。像这样保持两个字典同步会在每次操作上占用更多空间和时间,但您的操作会变得更便宜。
标签: c# dictionary foreach