【问题标题】:How to assign one value to multiple keys in a C# dictionary?如何为 C# 字典中的多个键分配一个值?
【发布时间】:2021-05-12 23:13:45
【问题描述】:

我想定义一个字母字典。在这本词典中,字符是键,并且为每个键分配了一个值。 我以最简单的方式编写了它,您可以看到一些键具有相同的值。

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}};

我需要找到其中的字母并使用分配的值。怎么写更简洁?

【问题讨论】:

  • 技术上你的做法是正确的,但一切都取决于你将如何使用字典。您需要通过字母查找值吗?或者您想按整数值查找所有字母?或者你可能需要别的东西,请详细说明你想如何使用字典。
  • 是的,我想搜索一个字母并为其分配值。因此,我将字母视为键。 @E.Shcherbo
  • 那么您可以使用您的解决方案,但是如果您担心代码的清洁度,您可以查看@Charlieface 的答案,但就个人而言,这让人感到困惑而不是帮助
  • 您也可以创建一个空字典,然后编写一个方法来接受键列表和您希望将键映射到的值。在该方法中,您只需将映射添加到每个键的值。 void MapValueToKeys(Dictionary&lt;char, int&gt; values, IEnumerable&lt;char&gt; keys, int value)
  • 要清楚,每个键具有相同的值不是问题(当然取决于域),想象一下电话簿,其中电话号码映射到人名。可以有两个人(两个不同的号码)并且同名。

标签: c# linq dictionary variable-assignment lookup


【解决方案1】:

Dictionary 是键和值的集合。在这个集合中,每个键只映射到一个值。并且已经在 System.Collection.Generics 命名空间中实现。

另一方面,有一个名为 Lookup 的集合,它表示键和值之间的一对多映射。 IE。它将一个键映射到一个或多个值,并且位于 System.Linq 命名空间中。

您可以转换任何在 System.Linq 命名空间中实现了 IEnumerable 接口和 ToLookup() 方法的集合来构造 Lookup 集合.

在有关 C# 语言的 Microsoft 教程中阅读有关 Lookup 集合和 Dictionary 的更多信息。

在这个问题中,我们可以考虑一个包含两个字段的包,一个句子中的“Alphabet”字符和它的“Counts”。

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

然后构造 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));
    }
 }

这有助于将“Counts”视为新键并为其分配多个“Alphabet”字符,它们的“Counts”值具有相同的数量!

【讨论】:

【解决方案2】:

使用此扩展方法:

    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);
    }

您可以像这样创建字典:

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

【讨论】:

    【解决方案3】:

    您可以为键创建值字典。 然后,您可以使用 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));
    

    【讨论】:

    • 我认为这里没有任何理由使用列表而不是数组
    • 正确你必须转换它。使用 var finalDict = new Dictionary(); tempDict.ForEach(x => x.Value.ForEach(y => finalDict[y] = x.Key));
    • (你可以在那里使用SelectMany
    猜你喜欢
    • 2021-04-08
    • 1970-01-01
    • 1970-01-01
    • 2020-03-01
    • 2012-04-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-09-07
    相关资源
    最近更新 更多