C# 字典:每个键都有相同的值 - 我可以删除冗余吗?

发布于 2024-08-13 13:32:05 字数 737 浏览 4 评论 0原文

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

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 不会不会引发插入重复键的尝试。

Consider the following code, where each key has an identical value:

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

My question:

  • Can I remove the redundancy, so that I don't have to repeat each
    string twice, similar to the
    following:
IDictionary<string, string> quarterbackDictionary = new Dictionary<string, string>();
quarterbackDictionary.Add("Manning");
quarterbackDictionary.Add("Brady");
quarterbackDictionary.Add("Rivers");

FYI:

  • I'm using a Dictionary because I want to throw on an attempt to insert a duplicate key.
  • A HashSet would not throw on an attempt to insert a duplicate key.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

梦幻的心爱 2024-08-20 13:32:05

您可以将 HashSet包装在您自己的类中,并且如果您尝试两次添加相同的键,则它会抛出异常。

定义该类不会很麻烦,事实上,这里有一个可能的实现,您可以调整它以满足您的需求:

    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 方法)。

You could wrap a HashSet<string> in your own class, and have it throw an exception if you try to add the same key twice.

It won't be much trouble to define that class, in fact, here is a possible implementation that you can tweak to fit your needs:

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

As the other answers mention, you could also make it an extension method. I think you could certainly do this, unless you need to be absolutely sure that you cannot add the same item twice (if you do it the extension method way, one could still call the regular .Add method).

岁月如刀 2024-08-20 13:32:05

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

Add an extension method to HashSet, say AddUnique, which just calls Add and throws if the return is false.

相守太难 2024-08-20 13:32:05

也许你可以使用扩展方法

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

Perhaps you could use an extension method

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);
    }
}
溺ぐ爱和你が 2024-08-20 13:32:05

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

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

Inherit from System.Collections.ObjectModel.Collection and override InsertItem (which is protected).

Then you can do your duplicate check and throw when someone inserts a duplicate item. InsertItem is called on any of the methods that can put in a new item: Add, Insert, etc.

孤寂小茶 2024-08-20 13:32:05

您还可以从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

You could also inherit from 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
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文