用于简单查找的.NET工具?

时间:2014-03-25 08:34:06

标签: c# .net dictionary lookup

所以我最近发现自己在这些方面编写代码。

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

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

这个例子过于笼统,但我发现自己的共同目标是“我已经完成了这个吗?”。

我喜欢使用Dictionary进行快速键查找,但由于我从不关心值字段,所以我不禁觉得它有点过分,即使每个条目只有一个字节。

是否有更好的.NET工具可以实现这一点,具有词典的键查找速度,但没有任意和不必要的值?

2 个答案:

答案 0 :(得分:4)

您应该使用HashSet<T>

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

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

缩短时间:

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

答案 1 :(得分:0)

没有相应的工具或库,但是您可以重构此代码以减少冗长。例如,可以使用Distinct方法简化代码原样

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

你可以使用某种ForEach extension method进一步重构它,或者将整个事物重构为扩展方法。

或者,如果您的要求略有不同(例如,您希望在应用程序的生命周期内保留dict),那么这可能会以稍微不同的方式重构,例如

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