以下是一个示例代码,演示如何遍历字典,并找到相同的值返回键:

using System;
using System.Collections.Generic;

class Program
{
    static void Main(string[] args)
    {
        Dictionary<string, int> dict = new Dictionary<string, int>
        {
            { 'A', 1 },
            { 'B', 2 },
            { 'C', 2 },
            { 'D', 3 },
            { 'E', 3 }
        };

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

        foreach (var pair in dict)
        {
            int value = pair.Value;
            string key = pair.Key;

            if (result.ContainsKey(value))
            {
                result[value].Add(key);
            }
            else
            {
                result[value] = new List<string> { key };
            }
        }

        foreach (var pair in result)
        {
            int value = pair.Key;
            List<string> keys = pair.Value;

            if (keys.Count > 1)
            {
                Console.WriteLine($'值为 {value} 的键有:');
                foreach (string key in keys)
                {
                    Console.WriteLine(key);
                }
            }
        }
    }
}

在上面的示例中,我们首先创建了一个字典 dict,其中包含了一些键值对。然后我们创建了一个新的字典 result,用于存储相同值的键。

接下来,我们使用 foreach 循环遍历原始字典 dict 中的每个键值对。对于每个键值对,我们提取出键和值,并检查 result 字典中是否已经存在相同的值。如果存在,我们将当前键添加到对应值的列表中;如果不存在,我们创建一个新的列表,并将当前键添加到列表中。

最后,我们再次使用 foreach 循环遍历 result 字典中的每个键值对,并打印出具有相同值的键。

运行上面的示例代码,将输出相同值的键:

值为 2 的键有:
B
C

值为 3 的键有:
D
E
C# 遍历字典,查找具有相同值的键

原文地址: https://www.cveoy.top/t/topic/bsvh 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录