【问题标题】:.NET collection that throws an exception when a duplicate is added添加重复项时引发异常的 .NET 集合
【发布时间】:2010-12-13 08:44:18
【问题描述】:

.NET 框架 (3.5) 中是否有一个集合(字典除外)在添加重复项时会引发异常?

HashSet 在这里不会抛出异常:

HashSet<string> strings = new HashSet<string>();
strings.Add("apple");
strings.Add("apple");

而字典是这样的:

Dictionary<string, string> dict = new Dictionary<string, string>();
dict.Add("dude", "dude");
dict.Add("dude", "dude"); //throws exception

编辑:是否有没有 (Key, Value) 的集合可以做到这一点?如果可能的话,我也想要 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);
        }
    }
}

【问题讨论】:

  • 好的,我看到你的编辑,我正在删除我原来的答案。要回答您的编辑,不。
  • 你不应该将'new'关键字添加到'Add'方法签名中,因为它隐藏了继承的成员HashSet.Add(T)。
  • 为什么不向 HashSet 添加扩展方法?像 AddRange/RemoveMany 会像 Linq(比如说 'Linq')

标签: .net collections unique duplicates


【解决方案1】:

但是如果值已经存在,HashSet.Add 方法会返回 false - 这还不够吗?

HashSet<string> set = new HashSet<string>();
...
if (!set.Add("Key"))
    /* Not added */

【讨论】:

  • 它允许您在一次调用中添加两个操作,而无需检查包含之前的成本。 Dictionary. 上没有 TryAdd
  • 我更喜欢它,但它很奇怪,因为 ICollection.Add 返回 void 和其他不允许重复的集合抛出...
  • 好的,我有点想要 AddRange 功能。谢谢
  • 糟糕...确实如此。
【解决方案2】:

如果您正在寻找AddRange 风格的功能,请查看C5。 C5 系列中的集合在其接口中公开了更多功能,包括一个函数AddAll,它接受一个可枚举,依次将可枚举中的所有项目添加到集合中。

编辑:还要注意C5 集合在适当的情况下实现了System.Collections.Generic ICollectionIList 接口,因此即使在需要这些接口的系统中也可以用作实现。

【讨论】:

    【解决方案3】:

    要添加到Bjorn 的答案,如果您还想要IList.AddRange 类型的函数与HashSet&lt;T&gt;,您可以使用HashSet&lt;T&gt;.UnionWith (from MSDN):

    HashSet(T).UnionWith 方法

    修改当前的 HashSet 对象以包含其自身、指定集合或两者中存在的所有元素。

    public void UnionWith(
        IEnumerable<T> other
    )
    

    唯一的问题可能是:我很确定这需要 .NET Framework 3.5 SP1 及更高版本。

    【讨论】:

      猜你喜欢
      • 2019-07-05
      • 2023-03-12
      • 2012-04-07
      • 1970-01-01
      • 2015-12-14
      • 2016-01-20
      • 1970-01-01
      • 2014-10-12
      • 1970-01-01
      相关资源
      最近更新 更多