Frage

So I've found myself writing code along these lines lately.

Dictionary<string, byte> dict = new Dictionary<string, byte>();

foreach(string str in arbitraryStringCollection)
{
  if(!dict.ContainsKey(str))
  {
    ProcessString(str);
    dict[str] = 0;
  }
}

The example is overly generic, but the common goal I find myself shooting for is "Have I done this one already?".

I like using Dictionary for the fast key lookup, but since I never care about the value field, I can't help but feel it's slightly excessive, even if it's just a byte per entry.

Is there a better .NET tool out there that accomplishes this, something with the key lookup speed of a Dictionary but without the arbitrary and unnecessary values?

War es hilfreich?

Lösung

You should use HashSet<T>

HashSet<string> hashSet= new HashSet<string>();

foreach(string str in arbitraryStringCollection)
{
    if(!hashSet.Contains(str))
    {
        ProcessString(str);
        hashSet.Add(str);
    }
}

To make it shorter:

foreach(string str in arbitraryStringCollection)
{
    if(hashSet.Add(str)) ProcessString(str);
}

Andere Tipps

There isn't a tool or library for that, however you can refactor this code to be less verbose. For example, the code as is could be simplified using the Distinct method.

foreach (var str in arbitraryStringCollection.Distinct())
{
    ProcessString(str)
}

You could further refactor it using some sort of ForEach extension method, or refactor the entire thing into an extension method.

Alternatively, if your requirements are slightly different (e.g. you want to keep dict for the lifetime of the application), then this could be refactored in a slightly different way, e.g.

HashSet<string> dict = new HashSet<string>();

foreach(string str in arbitraryStringCollection)
{
    dict.DoOnce(str, ProcessString);
}

// Re-usable extension method)
public static class ExtensionMethods
{
    public static void DoOnce<T>(this ISet<T> set, T value, Action<T> action)
    {
        if (!set.Contains(value))
        {
            action(value);
            set.Add(value);
        }
    }
}
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top