通过字典循环是否有"更好"或"更好的表现"方式

97l*_*ave 4 c# foreach dictionary

我循环遍历字符串列表,以查看该字符串是否包含在字典的值中,然后尝试从该值中删除该字符串.

目前我这样做:

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, "");
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

对我来说,这似乎有点长啰嗦.这样做有"更好"的方法吗?

seh*_*ehe 5

只需迭代底层IEnumerable的KeyvaluePair条目:

foreach (var kvp in formValues)
{
    if (kvp.Value != null && kvp.Value.Contains(preposition))
    {
        formValue[kvp.Key] = kvp.Value.Replace(preposition, "");
    }
}
Run Code Online (Sandbox Code Playgroud)

警告:在枚举集合时修改集合很少是一个好计划.在这种情况下,我说它没关系.

无论如何,

你真正想要实现的是多重替换.

为什么不使用正则表达式:

private static readonly myRegex = new Regex("at|as|if|of|the|to|a|an|it|is|by|its", 
                RegexOptions.Compiled | RegexOptions.IgnoreCase);

// ..

someValue = myRegex.Replace(someValue, "");
Run Code Online (Sandbox Code Playgroud)

我展示IgnoreCase以防万一你不知道.看起来它可能适用于您的代码.

  • 既然你有KVP,那就做`kvp.Value`而不是每次运行时从Dictionary中检索 (2认同)