本机 C# .NET 方法在添加之前检查集合中是否存在项目
我发现自己经常写这篇文章。
Hashtable h = new Hashtable();
string key = "hahahahaahaha";
string value = "this value";
if (!h.Contains(key))
{
h.Add(key, value);
}
是否有一个本机方法(可能类似于 AddIf() ??)来检查它是否存在于集合中,如果不存在,则将其添加到集合中?那么我的例子将更改为:
Hashtable h = new Hashtable();
string key = "hahahahaahaha";
string value = "this value";
h.AddIf(key, value);
这将适用于 Hastable 之外的情况。基本上任何具有 .Add 方法的集合。
编辑:更新为在添加到哈希表时添加值:)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
好吧,您可能不会编写该代码,因为
Hashtable
使用键/值对,而不仅仅是键。如果您使用 .NET 3.5 或更高版本,我建议您使用
HashSet< ;T>
,然后你就可以无条件调用Add
- 返回值将指示是否实际添加。编辑:好的,现在我们知道您正在谈论键/值对 - 没有任何内置条件添加(嗯,ConcurrentDictionary IIRC中有,但是......),但是如果如果您很乐意覆盖现有值,您可以只使用索引器:
与
Add
不同,如果已经有该键的条目,则不会引发异常 - 它只会覆盖它。Well, you probably don't write that code, because
Hashtable
uses key/value pairs, not just keys.If you're using .NET 3.5 or higher, I suggest you use
HashSet<T>
, and then you can just unconditionally callAdd
- the return value will indicate whether it was actually added or not.EDIT: Okay, now we know you're talking about key/value pairs - there's nothing built-in for a conditional add (well, there is in
ConcurrentDictionary
IIRC, but...), but if you're happy to overwrite the existing value, you can just use the indexer:Unlike
Add
, that won't throw an exception if there's already an entry for the key - it'll just overwrite it..NET框架中没有这样的方法。但您可以轻松编写自己的扩展方法:
对于 IDictionary,我使用此方法(通常用于
Dictionary>
及其变体):There isn't such a method in the .NET framework. But you can easily write your own extension method:
For IDictionary, I use this method (generally for
Dictionary<TKey, List<TValue>>
and variations):对于哈希表,您可以编写
myHashtable[key] = myHashtable[key] ?? newValue
,其中右侧首先检查myHashtable[key]
的计算结果是否为 null,如果没有解析为 null,否则解析为newVale
For a hashtable you could write
myHashtable[key] = myHashtable[key] ?? newValue
where the right hand side would first check ifmyHashtable[key]
evaluated to null and if not resolve to that otherwise resolve tonewVale
您的代码没有意义,因为哈希表需要键和值。
如果您指的是
HashSet
,那么如果该项已存在,则调用Add
将不会执行任何操作。如果您指的是
Dictionary
,您可以编写dict[key] = value
,如果键不存在,则添加该键;如果键存在,则覆盖它。Your code doesn't make sense, since a HashTable needs both a key and a value.
If you meant a
HashSet<T>
, callingAdd
will do nothing if the item is already there.If you meant a
Dictionary<TKey, TValue>
, you can writedict[key] = value
, which will add the key if it's not present or overwrite it if it is.到目前为止还没有。但是您可以编写自己的扩展方法来将其包装在一行中。
So far it doesn't .But you could write your own extension method to wrap this in one single line.
我经常在自定义的 Dictionary/Hashtable 集合中编写类似的方法,作为
类型 FetchOrCreate(Key)
,而不是void AddIf(Key)
I often write a similar method in my custom Dictionary/Hashtable collections, as a
Type FetchOrCreate(Key)
, not as anvoid AddIf(Key)