gpt4 book ai didi

c# - 是否有 "better"或 "better performance"循环遍历字典的方法

转载 作者:太空狗 更新时间:2023-10-30 00:52:51 26 4
gpt4 key购买 nike

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

目前我是这样做的:

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, "");
}
}
}
}

对我来说,这似乎有点啰嗦。有没有“更好”的方法来做到这一点?

最佳答案

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

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

警告:在枚举集合的同时修改集合很少是一个好的计划。在这种情况下,我想没问题。

无论如何,

您在这里真正想要实现的是多次替换。

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

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, "");

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

关于c# - 是否有 "better"或 "better performance"循环遍历字典的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19529024/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com