1

考虑以下代码,其中每个键具有相同的值:

IDictionary<string, string> quarterbackDictionary = new Dictionary<string, string>();
quarterbackDictionary.Add("Manning", "Manning");
quarterbackDictionary.Add("Brady", "Brady");
quarterbackDictionary.Add("Rivers", "Rivers");

我的问题:

  • 我可以删除冗余,这样我就不必重复每个字符串两次,类似于以下内容:
IDictionary<string, string> quarterbackDictionary = new Dictionary<string, string>();
quarterbackDictionary.Add("Manning");
quarterbackDictionary.Add("Brady");
quarterbackDictionary.Add("Rivers");

供参考:

  • 我正在使用字典,因为我想尝试插入重复键。
  • HashSet 不会尝试插入重复键。
4

5 回答 5

11

您可以将HashSet<string>包装在您自己的类中,如果您尝试两次添加相同的键,它会引发异常。

定义该类不会很麻烦,事实上,这是一个可能的实现,您可以调整以适应您的需求:

    public class UniqueHashSet<T> : ICollection<T>
    {
        private readonly HashSet<T> innerSet = new HashSet<T>();

        public void Add(T item)
        {
            if (innerSet.Contains(item))
                throw new ArgumentException("Element already exists", "item");
            innerSet.Add(item);
        }

        public void Clear()
        {
            innerSet.Clear();
        }

        public bool Contains(T item)
        {
            return innerSet.Contains(item);
        }

        public void CopyTo(T[] array, int arrayIndex)
        {
            innerSet.CopyTo(array, arrayIndex);
        }

        public bool Remove(T item)
        {
            return innerSet.Remove(item);
        }

        public int Count
        {
            get { return innerSet.Count; }
        }

        public bool IsReadOnly
        {
            get { return false; }
        }

        public IEnumerator<T> GetEnumerator()
        {
            return innerSet.GetEnumerator();
        }

        IEnumerator IEnumerable.GetEnumerator()
        {
            return innerSet.GetEnumerator();
        }
    }

正如其他答案所提到的,您也可以将其设为扩展方法。我认为您当然可以这样做,除非您需要绝对确定不能两次添加相同的项目(如果您以扩展方法的方式进行操作,仍然可以调用常规的 .Add 方法)。

于 2009-12-03T18:45:53.053 回答
3

向 HashSet 添加一个扩展方法,比如 AddUnique,它只调用 Add 并在返回为 false 时抛出。

于 2009-12-03T18:54:16.747 回答
1

你也可以继承自System.Collections.ObjectModel.KeyedCollection.

class MyDictionary : KeyedCollection<string, string>
{
    protected override string GetKeyForItem(string item)
    {
        return item;
    }
}

var d = new MyDictionary();
d.Add("jones");
d.Add("jones");   // this will except
于 2009-12-03T19:03:30.367 回答
1

从System.Collections.ObjectModel.Collection继承并覆盖InsertItem(受保护)。

然后,您可以进行重复检查并在有人插入重复项时抛出。在任何可以放入新项目的方法上调用 InsertItem:Add、Insert 等。

于 2009-12-03T18:48:59.943 回答
1

也许您可以使用扩展方法

public static class DictionaryExtensions
{
    public static void Add(this Dictionary<string, string> dictionary,  
        string keyAndValue)
    {
        string value;
        if (dictionary.TryGetValue(keyAndValue, out value))
        {
            throw new Exception();
        }

        dictionary.Add(keyAndValue, keyAndValue);
    }
}
于 2009-12-03T18:55:13.860 回答