在字典中找到最小键,并在c#中找到相同的值

问题描述 投票:-1回答:3

嗨,我想对我的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#中做到这一点在此先感谢

c# dictionary key-value-coding
3个回答
0
投票

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

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

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


0
投票
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}");

0
投票

这里是一种解决方案,它不能为每个键找到最小值。使用OrderBy()的排序是O(NLogN),而使用OrderBy()的排序是O(NLog])>。

Min()

输出:

Min()
© www.soinside.com 2019 - 2024. All rights reserved.