Search code examples
c#dictionarykey-value-coding

find minimum key in dictonary with same values in c#


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


Solution

  • 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.