C#字典类型具有独特的键和值 [英] C# dictionary type with unique keys and values

查看:119
本文介绍了C#字典类型具有独特的键和值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不知道是否有一个内置在C#类型是像'词典',但其中两个TKEY的,并TValue必须是唯一的。

I was wondering if there was a built in type in C# that was like 'Dictionary' but where both TKey and TValue had to be unique.

例如:

d.Add(1, "1");
d.Add(2, "1"); // This would not be OK because "1" has already been used as a value.

我知道这是一种异国情调,但似乎因为有在BCL大约十亿集合类型可能存在。任何想法?

I know this is kind of exotic, but it seems that since there are about a billion collection types in the BCL it might exist. Any ideas?

推荐答案

如何有字典和HashSet的/二次反向词典 - 这将解决该问题,并将在单字典进行检查比好

How about having Dictionary and HashSet/secondary reverse Dictionary - it will solve the issue and will perform better than checks on single Dictionary.

这样的事情,包装成类:

Something like this, wrapped as class:

HashSet<string> secondary = new HashSet<string>(/*StringComparer.InvariantCultureIgnoreCase*/);
Dictionary<int, string>dictionary = new Dictionary<int, string>();
object syncer = new object();

public override void Add(int key, string value)
{
  lock(syncer)
  {
    if(dictionary.ContainsKey(key))
    {
      throw new Exception("Key already exists");
    }

    if(secondary.Add(value)
    {
      throw new Exception("Value already exists");
    }
    dictionary.Add(key, value);
  }
}

这篇关于C#字典类型具有独特的键和值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆