C# 字典:每个键都有相同的值 - 我可以删除冗余吗?
考虑以下代码,其中每个键都有相同的值:
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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
您可以将 HashSet 包装在您自己的类中,并且如果您尝试两次添加相同的键,则它会抛出异常。
定义该类不会很麻烦,事实上,这里有一个可能的实现,您可以调整它以满足您的需求:
正如其他答案提到的,您也可以将其设为扩展方法。我认为你当然可以做到这一点,除非你需要绝对确定你不能添加相同的项目两次(如果你以扩展方法的方式这样做,人们仍然可以调用常规的 .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:
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).
向 HashSet 添加一个扩展方法,例如 AddUnique,它只调用 Add 并在返回 false 时抛出异常。
Add an extension method to HashSet, say AddUnique, which just calls Add and throws if the return is false.
也许你可以使用扩展方法
Perhaps you could use an extension method
继承 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.
您还可以从
System.Collections.ObjectModel.KeyedCollection
继承。You could also inherit from
System.Collections.ObjectModel.KeyedCollection
.