4

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

目前我这样做:

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

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

4

4 回答 4

5

只需迭代底层 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了以防万一你不知道。看起来它可能适用于您的代码。

于 2013-10-22T21:49:50.863 回答
1

我可能会做这样的事情:

Dictionary<string,string> Clean( Dictionary<string,string> dictionary , params string[] words )
{
  string pattern = @"\b(" + string.Join( "|" , words.Select( Regex.Escape ) ) + @")\b" ;
  Regex rx = new Regex(pattern,RegexOptions.IgnoreCase) ;

  foreach ( string key in dictionary.Keys )
  {
    dictionary[key] = rx.Replace(dictionary[key],"") ;
  }

  return dictionary ;
}
于 2013-10-22T22:11:55.653 回答
0

What about creating a automata in that each change in state is a specific character. Then if you want to find something you just have to follow the automata tree and get to the terminal point in which the searched thing lies.

于 2013-10-22T22:47:39.647 回答
0

在性能方面,您可能会考虑某种二叉搜索树,例如三叉搜索树。

于 2013-10-22T22:00:24.027 回答