gee*_*jay 10 .net collections unique duplicates
.NET框架(3.5)中是否有一个集合(除了字典),在添加副本时会抛出异常?
HashSet不会抛出异常:
HashSet<string> strings = new HashSet<string>();
strings.Add("apple");
strings.Add("apple");
Run Code Online (Sandbox Code Playgroud)
而词典确实:
Dictionary<string, string> dict = new Dictionary<string, string>();
dict.Add("dude", "dude");
dict.Add("dude", "dude"); //throws exception
Run Code Online (Sandbox Code Playgroud)
编辑:有没有(键,值)的集合这样做?如果可能的话我也想要AddRange ......
我推出了自己的:
public class Uniques<T> : HashSet<T>
{
public Uniques()
{ }
public Uniques(IEnumerable<T> collection)
{
AddRange(collection);
}
public void Add(T item)
{
if (!base.Add(item))
{
throw new ArgumentException("Item already exists");
}
}
public void AddRange(IEnumerable<T> collection)
{
foreach (T item in collection)
{
Add(item);
}
}
}
Run Code Online (Sandbox Code Playgroud)
Bjö*_*örn 14
但是如果值已经存在,HashSet.Add方法返回false - 还不够吗?
HashSet<string> set = new HashSet<string>();
...
if (!set.Add("Key"))
/* Not added */
Run Code Online (Sandbox Code Playgroud)