简体   繁体   English

如何为 C# 字典中的多个键分配一个值?

[英]How to assign one value to multiple keys in a C# dictionary?

I want to define a dictionary of alphabets.我想定义一个字母字典。 In this dictionary, the characters are keys and there are assigned a value for each one.在这本词典中,字符是键,并且为每个字符分配了一个值。 I have written it in the simplest way and as you can see some keys have the same values.我以最简单的方式编写了它,您可以看到一些键具有相同的值。

var testDict = 
        new Dictionary <char, int>() { 
            {'A', 1}, {'E', 1}, {'I', 1}, 
            {'O', 1}, {'U', 1}, {'L', 1}, 
            {'N', 1}, {'R', 1}, {'S', 1}, 
            {'T', 1}, 
            {'D', 2}, {'G', 2},
            {'B', 3}, {'C', 3}, {'M', 3}, {'P', 3}, 
            {'F', 4}, {'H', 4}, {'V', 4}, {'W', 4}, {'Y', 4}, 
            {'K', 5}, 
            {'J', 8}, {'X', 8}, 
            {'Q',10}, {'Z',10}};

I need to find the alphabets in it and use the assigned values.我需要在其中找到字母并使用分配的值。 How can I write it in a more concise way?我怎样才能以更简洁的方式编写它?

A Dictionary<TKey, TValue> is a collection of keys and values. Dictionary<TKey, TValue>是键和值的集合。 In this collection, each key is mapped to just one value.在这个集合中,每个键都映射到一个值。 And it has been implemented in the System.Collection.Generics namespace.它已在 System.Collection.Generics 命名空间中实现。

On the other hand, there is a collection named Lookup<TKey, TElement> which represents a one to many mapping between keys and values.另一方面,有一个名为Lookup<TKey, TElement>的集合,它表示键和值之间的一对多映射。 Ie it maps one key to one or more values, and it is in the System.Linq namespace.即它将一个键映射到一个或多个值,它位于 System.Linq 命名空间中。

You can convert any collections which have implemented the IEnumerable interface and the ToLookup() method in the System.Linq namespace to construct the Lookup<TKey, TElement> collection.您可以转换任何在 System.Linq 命名空间中实现了IEnumerable接口和 ToLookup() 方法的 collections 以构造Lookup<TKey, TElement>集合。

Read more about Lookup collection and Dictionary in the Microsoft tutorials about C# language.在有关 C# 语言的 Microsoft 教程中阅读有关查找集合和字典的更多信息。

In this question, we could consider a package consisting of two fields, the "Alphabet" character and its "Counts" in a sentence.在这个问题中,我们可以考虑一个 package,它由两个字段组成,一个句子中的“字母”字符和它的“计数”。

class Package
{
    public char Alphabet;
    public int Counts;
}

Then construct the Lookup data structure:然后构造 Lookup 数据结构:

public static void LookupExample()
{
    // Create a dictionary of Packages to put into a Lookup data structure.
    var testDict = new Dictionary <char, int>() { 
         new Package { Alphabet = 'A', Counts = 1},
         new Package { Alphabet = 'B', Counts = 3},
         new Package { Alphabet = 'C', Counts = 3},
         new Package { Alphabet = 'D', Counts = 2},
         new Package { Alphabet = 'E', Counts = 1},
         new Package { Alphabet = 'F', Counts = 4},
         new Package { Alphabet = 'G', Counts = 2},
         new Package { Alphabet = 'H', Counts = 4},
         new Package { Alphabet = 'I', Counts = 1},
         new Package { Alphabet = 'J', Counts = 8},
         new Package { Alphabet = 'K', Counts = 5},
         new Package { Alphabet = 'L', Counts = 1},
         new Package { Alphabet = 'M', Counts = 3},
         new Package { Alphabet = 'N', Counts = 1},
         new Package { Alphabet = 'O', Counts = 1},
         new Package { Alphabet = 'P', Counts = 3},
         new Package { Alphabet = 'Q', Counts = 10},
         new Package { Alphabet = 'R', Counts = 1},
         new Package { Alphabet = 'S', Counts = 1},
         new Package { Alphabet = 'T', Counts = 1},
         new Package { Alphabet = 'U', Counts = 1},
         new Package { Alphabet = 'V', Counts = 4},
         new Package { Alphabet = 'W', Counts = 4},
         new Package { Alphabet = 'X', Counts = 8},
         new Package { Alphabet = 'Y', Counts = 4},
         new Package { Alphabet = 'Z', Counts = 10}};
                                                         

    // Create a Lookup to organize the packages. Use the Counts of each Alphabet as the key value.
    // Select Alpahbet appended to each Counts in the Lookup.
    Lookup<int, char> lookup = (Lookup<int, char>)testDict.ToLookup(p => p.Counts, p => p.Alphabet);

    // Iterate through each IGrouping in the Lookup and output the contents.
    foreach (IGrouping<int, char> packageGroup in lookup)
    {
        // Print the key value of the IGrouping.
        Console.WriteLine(packageGroup.Key);
        // Iterate through each value in the IGrouping and print its value.
        foreach (char chr in packageGroup)
            Console.WriteLine("    {0}", Convert.ToString(chr));
    }
 }

This helps to consider the "Counts" as the new key and assign multiple "Alphabet" characters to it which have same amount for their "Counts" value!这有助于将“计数”视为新键并为其分配多个“字母”字符,它们的“计数”值具有相同的数量!

With this extension method:使用此扩展方法:

    public static void Add<TKey, TValue>(this Dictionary<TKey, TValue> dict, TValue value, params TKey[] keys)
    {
        foreach (var key in keys)
            dict.Add(key, value);
    }

You can create a Dictionary like this:您可以像这样创建字典:

    var testDict =
        new Dictionary<char, int>() {
                {1, 'A', 'E', 'I'},
                {2, 'D', 'G'},
                {3, 'B', 'C', 'M', 'P'},
        };

You can create a dictionary of value to keys.您可以为键创建值字典。 And then, you can use linq to convert it into a dictionary:然后,您可以使用 linq 将其转换为字典:

var tempDict = new Dictionary<int, List<char>>
{
    {1, new List<char> {'A', 'E','I'}},
    {2, new List<char> {'D','G'}}
};
var finalDict = new Dictionary<char, int>();
tempDict.ForEach(x => x.Value.ForEach(y => finalDict[y] = x.Key));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM