C# 字典:每个值有多个键

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19102954/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 14:05:45  来源:igfitidea点击:

C# Dictionary: Multiple KEYS per Value

c#.netmap

提问by user1818486

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

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

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).

这背后的原因是我想为每个“主”ID 保留多个 Item-ID(用于 Bot),并且将这些多个 ID 放入一个值中太慢而无法修改(寻找一个值 => 循环低谷所有主要 ID 并获取每个值,然后检查该 ID 是否存在)。

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

寻找价值应该返回:关键 1-4,而不是 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.

任何人都知道这是否可能以及如何做到这一点?提前致谢。

采纳答案by MatteKarla

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

反过来做字典,使值成为项目列表。

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

例如,如果Value是字符串并且Key 1-4是整数,则您的字典可能如下所示:

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

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

检索Value通过theDictionary["Value"]然后将返回含有1,2,3和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"];

回答by Andrew Coonce

Edit:Looking at your edit, it really looks like you have designed this Dictionarybackwards... your keys should be for matching values, not your values for matching keys.

编辑:查看您的编辑,看起来您确实是Dictionary向后设计的……您的键应该用于匹配值,而不是用于匹配键的值。

You could do something like create a dictionary that maps outer-keys to inner-keys, then use the inner-key to index a second dictionary.

你可以做一些事情,比如创建一个将外键映射到内键的字典,然后使用内键来索引第二个字典。

Example:

例子:

var outer = new Dictionary<int, Guid> {
  { 1, GuidA },
  { 2, GuidA },
  { 3, GuidA },
  { 4, GuidA },
  { 5, GuidB }
};
var inner = new Dictionary<Guid, Value> {
  { GuidA, Value1 },
  { GuidB, Value2 }
};

You would access it as: value = outer[inner[key]].

您可以通过以下方式访问它:value = outer[inner[key]]

回答by paulsm4

1) Servy is absolutely correct. If you're doing a search on anything but a key ... and if you're trying to retrieve anything but the corresponding value ... then something is definitely wrong. All things being equal, you probably DON'T want a dictionary.

1) Servy 是完全正确的。如果您正在搜索除键之外的任何内容......并且如果您试图检索除相应值之外的任何内容......那么肯定有问题。在所有条件相同的情况下,您可能不需要字典。

2) Based on what you're saying, perhaps a better collection type might be a List. Specifically, a list of name/value pairs.

2)根据您所说的,也许更好的集合类型可能是列表。具体来说,名称/值对的列表。

EXAMPLE:

例子:

List<string> NVList = new List<string>();
NVList.Add("color=blue");
...

3) Note that .Net has a specialized "NameValueCollection" class that might be IDEALfor you:

3) 请注意,.Net 有一个专门的“NameValueCollection”类,它可能对您来说是理想的:

回答by Dweeberly

You may be overthinking your problem. Keys need to be unique in order to be useful for lookup operations. Values do not need to be unique. Multiple keys can point to the same value without causing problems.

你可能多虑了你的问题。键必须是唯一的,以便对查找操作有用。值不需要是唯一的。多个键可以指向同一个值而不会引起问题。

回答by Chakrava

Assuming you have your initial dictionary (mapping your keys to values) already you can use some Linq to convert it into a reverse dictionary without having to create that reverse dictionary by hand.

假设您已经拥有初始字典(将键映射到值),您可以使用一些 Linq 将其转换为反向字典,而无需手动创建该反向字典。

var newDict = initialDict.Select(x=>x.Value).Distinct().ToDictionary(x=>x, x=> initialDict.Where(kvp=>kvp.Value == x).Select(kvp=>kvp.Key));

Select the distinct originalValuesfrom your original dictionary and use those as your newKeys. Your newValuesare the set of your originalKeysthat mapped to each originalValue/newKey.

选择与originalValues原始词典不同的内容并将其用作您的newKeys. 您newValuesoriginalKeys映射到每个originalValue/的集合newKey



Example: https://dotnetfiddle.net/dhwUSC

示例:https: //dotnetfiddle.net/dhwUSC

Given an initial dictionary of

给定一个初始字典

var initialDict = new Dictionary<int, string>{
        {1, "Value"},
        {2, "Value"},
        {3, "Value"},
        {4, "Value"},
        {5, "Value2"}
    };

the above function returns

上面的函数返回

Value: {1, 2, 3, 4}
Value2: {5}