【问题标题】:How to prevent duplicate values in a dictionary in c# .net [closed]如何防止 c# .net 中字典中的重复值 [关闭]
【发布时间】:2015-06-01 10:39:55
【问题描述】:

我有字典,其中值重复。如何防止字典中的重复?以下是我的代码

private class GcellGtrx
{
    public Gcell Gcell { get; set; }
    public Gtrx Gtrx { get; set; }
}
    private readonly Dictionary<int, GcellGtrx> _dictionary = new Dictionary<int, GcellGtrx>();

_dictionary.Add(gcell.CellId, gcellGtrx);

【问题讨论】:

  • CellId 是否应该包含重复项?
  • Yuval Itzchakov 不是独一无二的
  • 那怎么可能有重复的键呢?你实际上是如何调用你的代码的?
  • 他说 values 是重复的,而不是键。

标签: c# .net


【解决方案1】:

要检查重复键,您可以使用:

dictionary.ContainsKey(gcell.CellId);

要检查重复值,您可以使用:

dictionary.ContainsValue(gcellGtrx);

【讨论】:

    【解决方案2】:

    如果您可以接受扫描整个字典以查找可能的重复项的开销,那么此代码将检查字典中是否已经存在值:

    dictionary.ContainsValue(gcellGtrx);
    

    如果你不能接受,你应该:

    • 以相反的顺序创建两个类型的字典,基本上是一个从值到键的字典
    • 创建字典中值的哈希集

    然后这将是一个类似于您在普通字典上执行的查找以查看该值是否已经存在。

    即。你可以这样做:

    private readonly Dictionary<int, GcellGtrx> _dictionary = new Dictionary<int, GcellGtrx>();
    private readonly Dictionary<GcellGtrx, int> _reverseDictionary = new Dictionary<GcellGtrx, int>();
    
    if (!_reverseDictionary.ContainsKey(gcellGtrx))
    {
        _dictionary.Add(gcell.CellId, gcellGtrx);
        _reverseDictionary.Add(gcellGtrx, gcell.CellId);
    }
    

    【讨论】:

      【解决方案3】:

      要么

      _dictionary[gcell.CellId] = gcellGtrx;
      

      这将包含字典中的最后一个 gcellGtrx。

      GcellCtrx testCell;
      
      if (!_dictionary.TryGet(gcell.CellId, out testCell))
           _dictionary.Add(gcell.CellId, gcellGtrx);
      

      这将保留字典中的第一个 gcellGtrx。

      【讨论】:

        【解决方案4】:

        您可以在添加到字典之前检查重复值:

        if (!_dictionary.ContainsValue(gcellGtrx))
            _dictionary.Add(gcell.CellId, gcellGtrx);
        

        更新

        感谢@Lasse V. Karlsen,我编辑了我的答案,他提醒我我误读了这个问题。

        【讨论】:

        • 他说 values 是重复的,而不是键。基本上他希望字典防止重复值。由于字典本身仅使用键进行查找,因此没有内置功能来处理此问题。
        猜你喜欢
        • 2013-07-20
        • 2013-08-22
        • 1970-01-01
        • 2021-12-18
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-02-22
        • 1970-01-01
        相关资源
        最近更新 更多