嗨,我想对我的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}");