如何在c#.net中防止字典中出现重复值
我有一本字典,里面的值是重复的。如何防止字典中的重复?下面是我的代码如何在c#.net中防止字典中出现重复值,c#,.net,C#,.net,我有一本字典,里面的值是重复的。如何防止字典中的重复?下面是我的代码 private class GcellGtrx { public Gcell Gcell { get; set; } public Gtrx Gtrx { get; set; } } private readonly Dictionary<int, GcellGtrx> _dictionary = new Dictionary<int, GcellGtrx>(); _dicti
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);
专用类GcellGtrx
{
公共Gcell Gcell{get;set;}
公共Gtrx Gtrx{get;set;}
}
专用只读词典_Dictionary=新词典();
_dictionary.Add(gcell.CellId,gcellGtrx);
要检查重复密钥,您可以使用:
dictionary.ContainsKey(gcell.CellId);
dictionary.ContainsValue(gcellGtrx);
要检查重复值,可以使用:
dictionary.ContainsKey(gcell.CellId);
dictionary.ContainsValue(gcellGtrx);
在添加到字典之前,可以检查重复值:
if (!_dictionary.ContainsValue(gcellGtrx))
_dictionary.Add(gcell.CellId, gcellGtrx);
更新
感谢@Lasse V.Karlsen,他提醒我我误读了这个问题。我编辑了我的答案。
_dictionary[gcell.CellId] = gcellGtrx;
这将有字典中的最后一个gcellGtrx
或
这将保留字典中的第一个gcellGtrx。如果您可以接受扫描整个字典以查找可能的重复项的开销,则此代码将检查字典中是否已经存在一个现有值:
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);
}
private readonly Dictionary\u Dictionary=new Dictionary();
专用只读词典_reverseDictionary=新词典();
如果(!\u反向指令容器(gcellGtrx))
{
_dictionary.Add(gcell.CellId,gcellGtrx);
_添加(gcellGtrx,gcell.CellId);
}
CellId是否应该包含重复的内容?Yuval Itzhakov不,这是唯一的那么怎么可能存在重复的密钥?你实际上是如何调用代码的?他说值是重复的,不是键。他说值是重复的,不是键。基本上,他希望字典能防止重复值。因为字典本身只使用键进行查找,所以没有内置的功能来处理这个问题。