C# 您可以在 Dictionary 集合或其他类型的集合中拥有 2 个以上的项目吗?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/627442/
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-04 10:52:41  来源:igfitidea点击:

Can you have more than 2 items in a Dictionary collection or another type of collection?

c#collections

提问by Xaisoft

I doubt this is possible, but I was curious if you could have more than 2 items (key,value) in a dictionary. Maybe a key and 2 values. Is there a collection object that does allow this? What I am actually trying to do is to store a key and a value for the key and another value to hold the count of how many times the key has been found. For example, I may have a for loop that goes through a list of colors and each color has a unique value. As I go through the list, I not only want to store the color, the unique value of the color in a dictionary, but also store how many times red occurred in the list.

我怀疑这是可能的,但我很好奇字典中是否可以有 2 个以上的项目(键、值)。也许一个键和 2 个值。是否有允许这样做的集合对象?我实际上想要做的是存储一个键和一个键的值以及另一个值来保存键被找到的次数。例如,我可能有一个遍历颜色列表的 for 循环,每种颜色都有一个唯一的值。当我浏览列表时,我不仅要在字典中存储颜色、颜色的唯一值,还要存储列表中红色出现的次数。

I put in the following declaration and now I am tyring to figure out how I can test to see if it contains the value already and if it does not, add it to the list with a count of 1 and if it does, increment the count. After I post the declaration, I will post how I was doing it with just one dictionary.

我输入了以下声明,现在我很想弄清楚如何测试它是否已经包含该值,如果没有,请将其添加到列表中,计数为 1,如果包含,则增加计数. 在我发布声明后,我将发布我只使用一本字典的方式。

Dictionary<string, Dictionary<int,int>> colors = 
                          new Dictionary<string, Dictionary<int,int>>();

Here is code of how I was handling it before:

这是我之前如何处理它的代码:

Dictionary<string, int> colors = new Dictionary<string, int>();

 foreach (Color color in ColorList)
        {
            if (colors.ContainsKey(color.ToString()))
                colors[color]++;
            else
                colors.Add(color, 1);
        }

采纳答案by TheTXI

Could you perhaps have a dictionary of a struct that would keep track of the color and the number of times it occurred?

你能不能有一个结构的字典来跟踪颜色和它发生的次数?

Edit: As suggested elsewhere, this could also be accomplished by building your own small custom class. Would essentially work in the same fashion.

编辑:正如其他地方所建议的,这也可以通过构建您自己的小型自定义类来完成。基本上会以相同的方式工作。

回答by Pop Catalin

you can use two dictionaries for this or simply create a data class that has both the color and the count and store the intermediate class instances in a dictionary.

您可以为此使用两个字典,或者简单地创建一个具有颜色和计数的数据类,并将中间类实例存储在字典中。

回答by Brent Miller

You're looking for a MultiMap.

您正在寻找 MultiMap。

I wrote the following (not fully tested):

我写了以下内容(未完全测试):

 using System.Collections.Generic;

public class MultiMapSet<TKey, TValue>
{
    private readonly Dictionary<TKey, HashSet<TValue>> _ht = new Dictionary<TKey, HashSet<TValue>>();

    public void Add(TKey key, TValue value)
    {
        HashSet<TValue> valueSet;
        if (_ht.TryGetValue(key, out valueSet))
        {
            valueSet.Add(value);
        }
        else
        {
            valueSet = new HashSet<TValue> { value };
            _ht.Add(key, valueSet);
        }
    }

    public bool HasValue(TKey key, TValue value)
    {
        HashSet<TValue> valueSet;
        if (_ht.TryGetValue(key, out valueSet))
        {
            return valueSet.Contains(value);
        }
        return false;
    }

    public HashSet<TValue> GetValues(TKey key)
    {
        HashSet<TValue> valueSet;
        _ht.TryGetValue(key, out valueSet);
        return valueSet;
    }

    public void Remove(TKey key, TValue value)
    {
        HashSet<TValue> valueSet;
        if (!_ht.TryGetValue(key, out valueSet))
        {
            return;
        }

        if (valueSet.Contains(value))
        {
            valueSet.Remove(value);
        }
    }
}

回答by itsmatt

Well, one way would be to have:

好吧,一种方法是拥有:

Dictionary<key, KeyValuePair<value, int>>

If I'm understanding your question.

如果我理解你的问题。



编辑:

Actually, if the color and value were consistent - meaning that 'red' was always 3 or 19 or whatever you used as the value of red, then the name 'red' and the value, say 19, is really just a compound key and so you could do something like this:

实际上,如果颜色和值是一致的——意味着“红色”总是 3 或 19 或任何你用作红色值的东西,那么名称“红色”和值,比如 19,实际上只是一个复合键和所以你可以做这样的事情:

Dictionary<KeyValuePair<string, int>, int> mydict;

and then for updates do something like this:

然后为更新做这样的事情:

mydict[key] = mydict[key] + 1;

回答by womp

You could make a simple Tuple class, such as a Triple. It's essentially a generically keyed dictionary but holds an additional object. It's pretty common for this scenario, people have made libraries that extend it out for 4 to 10 objects. Here's an example:

您可以创建一个简单的 Tuple 类,例如 Triple。它本质上是一个通用键控的字典,但包含一个额外的对象。这种情况很常见,人们已经制作了将其扩展为 4 到 10 个对象的库。下面是一个例子:

    public struct Triple<X, Y, Z>
    {
        public X First;     
        public Y Second;    
        public Z Third;     

        public Triple(X x, Y y, Z z)
        {
            First = x;
            Second = y;
            Third = z;
        }
    }

And then use it like so:

然后像这样使用它:

 var myTriple =  new Triple<string, Color, int>(
                        "key", 
                        myColor, 
                        count
                    )

,

,

回答by Crash893

could you do something like

你能做类似的事情吗

Dictonary<string,string> dh = new dictonary<string,string>();

dh.add("x","Something:0");


foreach keyvaluepair kvp in dh
{

    if kvp.key == x
    {
        string[] hold= kvp.value.split(':');
        //to update it the count it would be something like

        int y = convert.toint(hold[1])+1;
        kvp.value=hold[0]+":"+y.tostring();

     }

}

回答by Jeff Keslinke

Most of these answers all say pretty much the same (correct) thing. Just make the value of your 'outer' dictionary some sort of object you find most useful to doing what you need with. Personally without thinking about it I'd have gone with a dictionary of dictionary.

大多数这些答案都说几乎相同(正确)的事情。只需将您的“外部”字典的值设为某种您认为对完成您需要的最有用的对象即可。就个人而言,我会毫不犹豫地使用字典字典。

Dictionary<key1, Dictionary<key2, value>>

回答by sad47

Since C# 4.0 there is Tupleclass, that rovides static methods for creating tuple objects.

由于 C# 4.0 有Tuple类,它提供了用于创建元组对象的静态方法。

See: http://msdn.microsoft.com/en-us/library/system.tuple.aspx

请参阅:http: //msdn.microsoft.com/en-us/library/system.tuple.aspx

// Create a 7-tuple. 
var population = new Tuple<string, int, int, int, int, int, int>(
                           "New York", 7891957, 7781984, 
                           7894862, 7071639, 7322564, 8008278);
// Display the first and last elements.
Console.WriteLine("Population of {0} in 2000: {1:N0}",
                  population.Item1, population.Item7);
// The example displays the following output: 
//       Population of New York in 2000: 8,008,278 
//       Population of New York in 2000: 8,008,278

回答by user1089345

Dictionary> KeyValuePair = new Dictionary>();

字典> KeyValuePair = 新字典>();

KeyValuePair.Add("LoadType", new List { "PassiveLoad", "SocketLoad" });

KeyValuePair.Add("LoadType", new List { "PassiveLoad", "SocketLoad" });