在 C# 中查找具有相同值的字典中的最小键

find minimum key in dictonary with same values in c#

你好,我想对我的 C# 字典进行排序,以在 C# 字典中找到具有相同值的最低键 我的字典值看起来像

    [4, 29]
    [7, 29]
    [10, 32]
    [1, 32]
    [8, 32]
    [9, 38]
    [2, 38]

我想要这样的结果>

    4 is the lowest key for the same value 29
    1 is the lowest key for the same value 32
    2 is the lowest key for the same value 38

我已经尝试过 foreach 循环,但它似乎非常困难和复杂 在 C# 中是否有一些简单的方法可以做到这一点 提前致谢

这是针对您的问题的解决方案:

d.GroupBy(kvp => kvp.Value)
    .Select(grouping => $"{grouping.OrderBy(kvp => kvp.Key).First()} is the lowest key for the same value {grouping.Key}");

它使用 LINQ 按值对字典条目进行分组,然后在每个分组中找到最小的键。

var result = dictionary.GroupBy(x => x.Value)
   .Select(g => g.OrderBy(x => x.Key).First()); 

测试:

foreach(var item in result)
    Console.WriteLine($"{item.Key} is the lowest key for the same value {item.Value}");

这是一个解决方案,它不为每个键查找最小值进行排序。使用 OrderBy() is O(NLogN), whereas using Min() 排序是 O(N).

var grouped = d
    .GroupBy(x => x.Value)
    .Select(grp => (grp.Key, grp.Min(grp => grp.Key)));

foreach (var (Key, Min) in grouped)
{
    Console.WriteLine($"{Min} is the lowest key for the same value {Key}");
}

输出:

4 is the lowest key for the same value 29
1 is the lowest key for the same value 32
2 is the lowest key for the same value 38