97ldave
97ldave

Reputation: 5249

Is there a "better" or a "better performance" way of looping though a dictionary

I am looping through a list of strings to see if that string is contained in the values of a dictionary and then trying to remove that string from the value.

Currently I do it like this:

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

To me, this seems a bit long winded. Is there a "better" way of doing this?

Upvotes: 4

Views: 313

Answers (4)

ToxiCore
ToxiCore

Reputation: 157

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.

Upvotes: 0

Nicholas Carey
Nicholas Carey

Reputation: 74177

I'd probably do something like this:

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 ;
}

Upvotes: 1

Kirill Polishchuk
Kirill Polishchuk

Reputation: 56162

In terms of performance you might consider some kind of binary search tree, e.g. Ternary search tree.

Upvotes: 0

sehe
sehe

Reputation: 392833

Just iterate the KeyvaluePair entries of the underlying IEnumerable:

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

Warning: modifying a collection while enumerating it is rarely a good plan. In this case, I supose it's ok.

Anyways,

what you are really trying to achieve here is a multiple-replace.

Why not use a regular expression:

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

I showed IgnoreCase just in case you didn't know about that. It looks like it could be applicable to your code.

Upvotes: 5

Related Questions