C#字典:每个值有多个KEYS [英] C# Dictionary: Multiple KEYS per Value

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

问题描述

我正在寻找一种通过单个获取多个的方法。是的,我已经使用过搜索功能,但是大多数答案都是相反的方向(每个有多个),但我想相反。



其背后的原因是,我想为每个主 ID保留多个Item-ID(用于Bot),并将这些多个ID放入一个ID中的值太慢了进行修改(寻找一个值=>遍历所有主要ID并获取每个值,然后检查该ID是否存在)。



示例

 键1 =>值
键2 =>值
键3 =>值
键4 =>值
键5 =>价值2

寻找价值应返回:键1-4,而不是5



所以我正在寻找一种更轻松的方法-就像我上面所说的。



任何人都知道这是否可行以及如何会吗
预先感谢。

解决方案

用另一种方法来做字典,并将值设为项目列表。 / p>

例如,如果 Value 是字符串,并且键1-4 是您的字典的整数,可能看起来像这样:

  var theDictionary = new Dictionary< string,List< int>>( ); 

通过值 > theDictionary [ Value] 然后将返回包含1、2、3和4的整数的列表。



编辑-添加了示例:

  var theDictionary = new字典< string,List< string>> 
{
{值,新列表< string> {键1,键2,键3,键4,键5,}},
{ Value2,新列表< string> {键5,键2}}
};

var oneToFour = theDictionary [ Value];


I'm looking for a way to get multiple keys with a single value. Yes, I've already used the search function, but most answers are for the opposite direction (multiple values per key), but I want the opposite.

The reasoning behind this is that I want keep multiple Item-IDs (it's for a Bot) per "main" ID, and throwing those multiple IDs into a value of the one is too slow to modify (looking for one value => looping trough all main IDs & getting each value, then checking if that ID exists).

Example

Key 1 => Value
Key 2 => Value
Key 3 => Value
Key 4 => Value
Key 5 => Value 2

Looking for Value should return: Key 1-4, not 5

So I'm looking for a way to do that easier - like I said above.

Anyone knows if that's possible and how to do it? Thanks in advance.

解决方案

Do the dictionary the other way around and make the value a list of items.

if for example Value is a string and Key 1-4 are ints your dictionary could look something like:

var theDictionary = new Dictionary<string, List<int>>();

retrieving Value by theDictionary["Value"] would then return a list of ints containing 1, 2, 3 and 4.

Edit - Added example:

var theDictionary = new Dictionary<string, List<string>>
    {
        {"Value", new List<string> {"Key 1", "Key 2", "Key 3", "Key 4", "Key 5",}},
        {"Value2", new List<string> {"Key 5", "Key 2"}}
    };

var oneToFour = theDictionary["Value"];

这篇关于C#字典:每个值有多个KEYS的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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