如何防止 C# .NET 中字典中的重复值 [已关闭]

问题描述 投票:0回答:4

我有一本字典,其中的值是重复的。

如何防止字典中重复?

这是我的代码:

private class GcellGtrx
{
    public Gcell Gcell { get; set; }
    public Gtrx Gtrx { get; set; }
}

Dictionary<int, GcellGtrx> dictionary = new Dictionary<int, GcellGtrx>();

dictionary.Add(gcell.CellId, gcellGtrx);
c# .net dictionary duplicates
4个回答
10
投票

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

dictionary.ContainsKey(gcell.CellId);

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

dictionary.ContainsValue(gcellGtrx);

5
投票

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

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);
}

2
投票

都可以

_dictionary[gcell.CellId] = gcellGtrx;

这将具有字典中的最后一个 gcellGtrx。

GcellCtrx testCell;

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

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


1
投票

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

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

更新

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

© www.soinside.com 2019 - 2024. All rights reserved.