find minimum key in dictonary with same values in c#

176 Views Asked by At

hi i want to sort my c# dictonary to find the lowest key with same values in c# dictonary my dictionary values looks like

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

i want the result like this >

    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

i have tried with foreach loops but it seems very difficult and complicated is there is some easy way to do this in c# Thanks in advance

3

There are 3 best solutions below

0
Daniel Crha On BEST ANSWER

This is a solution for your issue:

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

It uses LINQ to group the dictionary entries by value, and then find the smallest key within each grouping.

0
Ashkan Mobayen Khiabani On
var result = dictionary.GroupBy(x => x.Value)
   .Select(g => g.OrderBy(x => x.Key).First()); 

Test:

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

Here is one solution that doesn't sort to find the smallest value for each key. Sorting using OrderBy() is O(NLogN), whereas using Min() is 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}");
}

Output:

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