Click here to Skip to main content
15,891,597 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
Get Maximum value based on the key
Dictionary <string long=""> test
test may contains
{
 { "val1",10},
{ "val2",20},
{"val1",50},
{val3,100}
{val1,150}
}


What I have tried:

i use max i cant get by key

d.Keys.Max()

var fooDict = new Dictionary<string,>();
var keyForBiggest = fooDict.MaxBy(kvp => kvp.Value).Key;
var biggestInt = fooDict[keyForBiggest];
Posted
Updated 5-Oct-20 21:02pm
v2
Comments
PIEBALDconsult 29-Feb-16 9:08am    
That's not how to use a Dictionary. You'll want a different structure if you need to do that a lot.
BulletVictim 29-Feb-16 9:29am    
try:
Declare variable x = 0;
for each the dictionary.
check if the value is bigger than x.
if bigger than x set x = value.
Matt T Heffron 29-Feb-16 13:42pm    
What you have shown, besides not compiling (two of the keys are not strings), it will also fail at run time since you are attempting to have three entries with the same "val1" key. This is not allowed. Dictionary requires that all keys be unique.
You probably need something like Dictionary<string, List<long>>

Try with below code:
C#
Dictionary<string, int> locations = new Dictionary<string, int>()
{
   { "test1", 4},
   { "test3", 9},
   { "test2", 1},
   { "test5", 2},
   { "test9", 3}
};

// To get max value in dictionary
int maxValue = locations.Max(); //9

// To get max value key name in dictionary
var guidForMaxDate = locations.FirstOrDefault(x => x.Value == locations.Values.Max()).Key; //test3
 
Share this answer
 
First of all, a test dictionary can NOT contains such of values:
{"val1",10},
{"val2",20},
{"val1",50},
{"val3",100}
{"val1",150}

because a val1 already exists!

You have to chenge your dictionary object to this definition:
C#
Dictionary <int, string> test = new Dictionary<int, string>()
		{
			{10, "val1"},
			{20, "val2"},
			{50, "val1"},
			{100, "val3"},
			{150, "val1"}
		};

Above code will create dictionary object as follow:
C#
Key Value
10  val1 
20  val2 
50  val1 
100 val3 
150 val1 


If you would like to return max for value equal to "val1", you can use Linq:
C#
var maxKeyOnValue = test.Where(c=>c.Value.Equals("val1")).Select(x=>x.Key).Max();
//returns 150


Another idea is to use SortedDictionary[^].
 
Share this answer
 
v3

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900