Link to home
Start Free TrialLog in
Avatar of Isabell
Isabell

asked on

Getting the Keys by the value in Dictionary

Hi,

I have a dictionary:
Dictionary<int, int> dict = new Dictionary<int, int>();

Open in new window

I want to get the key(s) that has the max value.
I used it as follow:

var max = dict.FirstOrDefault(x=>x.Value==maxValue).Key;

Open in new window


But this will return the first key only.
For example, if
maxValue=5 

Open in new window

and associated keys are 1 and 4, I want to print out both 1 and 4.

How can I accomplish this?
ASKER CERTIFIED SOLUTION
Avatar of kaufmed
kaufmed
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Please define "maxValue"..

E.g.

namespace ConsoleCS
{
    using System;
    using System.Collections.Generic;
    using System.Linq;

    public static class EnumHelper
    {
        public static void ToConsole<T>(this IEnumerable<T> @this)
        {
            foreach (T item in @this)
            {
                Console.WriteLine(item);
            }
        }
    }

    public class Program
    {
        public static void Main(string[] args)
        {
            Dictionary<int, int> dictionary = new Dictionary<int, int>();
            dictionary.Add(1, 1);
            dictionary.Add(2, 2);
            dictionary.Add(3, 3);
            dictionary.Add(4, 2);
            dictionary.Add(5, 3);
            dictionary.Add(6, 2);
            dictionary.Add(7, 1);

            int maxValue = int.MinValue;
            foreach (KeyValuePair<int, int> kvp in dictionary)
            {
                if (kvp.Value > maxValue)
                {
                    maxValue = kvp.Value;
                }
            }

            dictionary
                .Where(kvp => kvp.Value == maxValue)
                .ToConsole<KeyValuePair<int, int>>();

            Console.WriteLine("Done.");
            Console.ReadLine();
        }
    }
}

Open in new window