在添加之前检查项目是否存在于集合中的本地C#.NET方法

Rya*_*yer 7 c# collections

我发现自己经常写这篇文章.

Hashtable h = new Hashtable();
string key = "hahahahaahaha";
string value = "this value";
if (!h.Contains(key))
{
    h.Add(key, value);
}
Run Code Online (Sandbox Code Playgroud)

是否有一个本机方法(可能类似于AddIf()??)检查它是否存在于集合中,如果不存在,则将其添加到集合中?那么我的例子将改为:

Hashtable h = new Hashtable();
string key = "hahahahaahaha";
string value = "this value";
h.AddIf(key, value);
Run Code Online (Sandbox Code Playgroud)

这将适用于Hastable.基本上任何具有.Add方法的集合.

编辑:更新为添加到Hashtable时添加值:)

Jon*_*eet 15

好吧,您可能不会编写代码,因为Hashtable使用键/值对,而不仅仅是键.

如果您使用的是.NET 3.5或更高版本,我建议您使用HashSet<T>,然后您可以无条件调用Add- 返回值将指示它是否实际添加.

编辑:好的,现在我们知道你在谈论键/值对 - 没有任何内置的条件添加(嗯,有ConcurrentDictionaryIIRC,但......),但如果你很乐意覆盖现有的值,你可以只使用索引器:

h[key] = value;
Run Code Online (Sandbox Code Playgroud)

不同的是Add,如果已经存在密钥条目,它将不会抛出异常 - 它只会覆盖它.


the*_*oop 8

.NET框架中没有这样的方法.但是您可以轻松编写自己的扩展方法:

public static void AddIfNotExists<T>(this ICollection<T> coll, T item) {
    if (!coll.Contains(item))
        coll.Add(item)
}
Run Code Online (Sandbox Code Playgroud)

对于IDictionary,我使用此方法(通常用于Dictionary<TKey, List<TValue>>和变体):

public static TValue AddIfNotExists<TKey, TValue>(this IDictionary<TKey, TValue> dict, TKey key)
    where TValue : new()
{
    TValue value;
    if (!dict.TryGetValue(key, out value))
    {
        value = new T();
        dict.Add(key, value);
    }
    return value;
}
Run Code Online (Sandbox Code Playgroud)