我有一本字典,其中的值是重复的。
如何防止字典中重复?
这是我的代码:
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);
要检查重复密钥,您可以使用:
dictionary.ContainsKey(gcell.CellId);
要检查重复值,您可以使用:
dictionary.ContainsValue(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);
}
都可以
_dictionary[gcell.CellId] = gcellGtrx;
这将具有字典中的最后一个 gcellGtrx。
或
GcellCtrx testCell;
if (!_dictionary.TryGet(gcell.CellId, out testCell))
_dictionary.Add(gcell.CellId, gcellGtrx);
这会将第一个 gcellGtrx 保留在字典中。
您可以在添加到字典之前检查重复值:
if (!_dictionary.ContainsValue(gcellGtrx))
_dictionary.Add(gcell.CellId, gcellGtrx);
更新
感谢@Lasse V. Karlsen,我编辑了我的答案,他提醒我我误读了这个问题。