c#


How to find the key which has the highest value in a c# dictionary? [duplicate]


This question already has an answer here:
How to use LINQ to select object with minimum or maximum property value
8 answers
I have a Dictionary and I want to find the key which has the highest value.
For example if I had
Key | Value
a | 1
b | 2
c | 3
I would want c to be returned.
I have this at the moment but it only searches for the highest value, I'm not sure how to return the key.
var max = occurrences.Max(x => x.Value);
var maxKey = occurrences.OrderByDescending(x => x.Value).First().Key;
You need to include MoreLinq and use MaxBy
var result = occurrences.MaxBy(kvp => kvp.Value).Key;
Here are some approaches you can use.
Using LINQ as follows:
var max = myDictionary.Aggregate((l, r) => l.Value > r.Value ? l : r).Key;
By using LINQ, you can first identify the largest value then search for it:
var maxValue = myDictionary.Values.Max();
var max = myDictionary.Where(pair => maxValue.Equals(pair.Value)) .Select(pair => pair.Key);
Or this way:
var max = from x in myDictionary where x.Value == myDictionary.Max(v => v.Value) select x.Key;
var dict = new Dictionary<string,int>();
dict.Add("a",1);
dict.Add("b",2);
dict.Add("c",3);
var max= dict.OrderByDescending(x => x.Value).FirstOrDefault();
Remember to check if max is null.
Also here is a solution that consider if there were more than one key with the max value in the dictionary?
Dictionary<char, int> dic = new Dictionary<char, int>();
dic.Add('a', 1);
dic.Add('b', 2);
dic.Add('c', 3);
dic.Add('d', 3);
var maxValue = (int)dic.Max(i => i.Value);
List<char> maxKeys = dic.Where(i => i.Value == maxValue).Select(i => i.Key).ToList();

Related Links

Check permission of a PDF using itext [duplicate]
Is there an event fired when WebBrowser content is redrawn?
How can I filter a DataTable without brute-forcing it?
Creating objects using an older version of Google Protobuf
WPF Combo box not calling setter method when item changed
Entity RemoveRange delete all rows
zip is not working in the same way on 4.2 to 6.0
Twilio Error - 12300 - Invalid Content Type only sometimes
Range validation in the Form Designer's PropertyGrid of a shadowed property
SaveChanges without AcceptChanges
AppHarbor c# 4.6.1 higher version than exists in current target framework
MonoGame - RenderTarget2D drawn below sprites and in the wrong location
WPF TreeView context menu is disabled if no items exist
Flipping tile game
Input string is not correct format when trying to sum gridview column value
How to change the label color of an IntField - Unity

Categories

HOME
alasql
system-calls
qemu
windows-server-2008
opencv4android
salesforce-lightning
overrides
promotions
ionic-native
software-collections
normals
velocity
ldap-query
minimum
webseal
windows-phone
virtuemart
draw2d
jq
descriptor
inline-assembly
aws-iot
advertising
rancher
scripting-language
angular-schema-form
spock
jbossfuse
apm
lines
login-required
gitosis
outlook-2010
abide
anypoint-studio
mapquest
ng-lightning
server-side-swift
ui-grid
mixed-models
file-descriptor
android-graphview
quartz
colorbox
weld
import.io
runtime-permissions
cancan
enet
wink
android-vectordrawable
grib
cedar-bdd
mac-app-store
vga
particle-system
normalisation
recurring
android-xmlpullparser
supervised-learning
3d-rendering
jmh
chomsky-normal-form
video-embedding
google-finance-api
wonderware
dynamics-nav
computability
kramdown
dpkt
avrcp
tokudb
firewire
euro
esb-toolkit-2.1
dockerpy
numerical-recipes
backtrace
esri-arc-engine
qxorm
jsonmodel
conditional-comments
im4java
ccmenuitem
serializer
git-subtree
8-puzzle
violation
jython-2.5
auctex
m3u
animationdrawable
scriptmanager
jqzoom
mediastreamsource
subdirectories
nstoolbar
jquery-attributes
pixel-bender
j++

Resources

Mobile Apps Dev
Database Users
javascript
java
csharp
php
android
MS Developer
developer works
python
ios
c
html
jquery
RDBMS discuss
Cloud Virtualization
Database Dev&Adm
javascript
java
csharp
php
python
android
jquery
ruby
ios
html
Mobile App
Mobile App
Mobile App