.NET字典,带有两个键和一个值 [英] .NET dictionary with two keys and one value

查看:68
本文介绍了.NET字典,带有两个键和一个值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

.NET中是否有可用的词典,可以容纳2个键和一个值. 喜欢

Is there a dictionary available in .NET that could hold 2 keys and one value. Like

Dictionary(Of TKey, Of TKey, TValue)

我需要存储两个键,有时需要按键1查找项目,而有时按键2查找项目.

I have a need to store two keys and at certain times look an item by the key 1 and at other times by the key 2.

我当前的解决方案是维护两个字典

My current solution is to maintain two dictionaries

Dictionary<string, long> Dict1 = new Dictionary<string, long>();
Dictionary<long, long> Dict2 = new Dictionary<long, long>();

,当需要添加项目时,我会将其添加到两个字典中.

and when need to add item I will add it to both dictionaries.

Dict1.Add("abc", 111);
Dict2.Add(345, 111);

然后,我将根据需要查找的键之一从那些词典中的任意一个查找项目.

and then I will look up an item from either one of those dictionaries depending by which one of the keys I need to look by.

与删除或更新项目时的操作相同.

Same I will do when deleting or updating an item.

我已经考虑过组合键,但是我不知道如何设置它,并且我不想失去任何搜索该项的速度.

I have thought about the composite key but I don't know how to set it up and I don't want to lose any speed of searching the item.

.NET中是否有一些可用的解决方案来使字典可以容纳多个键?

Is there some solution available in .NET to have dictionary that can hold multiple keys?

推荐答案

由于您希望通过任一键都可以找到"值,所以我将像现在一样使用两个字典. 不过,我会将其包装在一个类中,使用方法名称如FindByXXXFindByYYY.

As you wish your value to be "findable" from either key, I would just use two dictionaries like you are doing now. However I would wrap this up in a class, with methods names like FindByXXX and FindByYYY.

更难的问题是如何进行删除,因为在删除时您需要知道两个密钥.也许您的值存储了两个键,所以您可以将值传递给delete方法.也许您永远不需要从词典中删除项目.或者需要删除项目的代码同时知道两个键.

The much harder question is how do you do a delete, as you need to know both keys at the time of the delete. Maybe your value stores both keys so you can pass the value into your delete method. Maybe you never need to remove items from the dictionaries. Or the code that needs to remove items knows both keys.

因此,由于每个用户的要求各不相同,因此没有标准的字典可以执行此操作.

Hence there is no standard dictionary to do this, as the requirements are different between each user.

(请注意,您不希望带有复合键的字典,因为这将要求您在希望查找某项时都必须知道两个键.)

这篇关于.NET字典,带有两个键和一个值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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