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

C# Boolean outside method won't read
Do Windows API EnumWindows and EnumChildWindows functions behave differently in Windows XP and 7
Detect open database connections
Splitting up A* pathing of many units into seperate game frames
How do I check if more than one enum flag is set?
Outlook Export Distribution Lists + items included with C#
.net application encountered error 0xc000142 when run on win2003 x64 sp2 enviroment
how to get required cell data in excel file using OleDb in c#?
From Java to C++ or C# [closed]
DataGridTemplateColumn with CheckBox
Can't rebuild my application anymore
delete S3 object
Comparing two tables for difference
nvarchar(max) field is empty when I insert ~81192 characters in it on SQL Server
How can C# use a legacy DLL simply without registration(regsvr32)
How can List<DerivedClass> be assigned to IEnumerable<BaseClass> parameter?

Categories

HOME
asterisk
pact
intellij-idea
cxf
dronekit
okhttp3
google-docs-api
ebay
mediarecorder
psexec
atlassian-fisheye
vichuploaderbundle
camunda
comma
web-testing
jsfiddle
facebook-marketing-api
css-float
filehelpers
hapijs
legend-properties
gpo
summernote
keystone
include-path
procedural-generation
uipath
workflow-foundation
uibarbuttonitem
csproj
boost-log
traitsui
matrix-multiplication
byobu
file-descriptor
java-5
php-mongodb
vpython
bootstrap-carousel
ocpjp
niagara-ax
weld
vertex
ajv
richtext
ios-keyboard-extension
stripes
visual-web-developer
git-push
cexception
nugetgallery
containstable
bluetooth-lowenergy-4.2
askbot
commercetools
database-project
jts
transbase
avrcp
joomla3.3
cakephp-2.6
veeam
accpac
chunks
sony-xperia
esri-arc-engine
crystal-reports-7
apache-pivot
api-eveonline
gnip
smartxls
traceur
rssi
flask-mongoengine
randomaccessfile
angularjs-select2
source-depot
android-library
ncml
idoc
dancer
zend-validate
overlays
object-tag
llblgen
iphone-maps
dongle
web-search
mdd
bootstrap-protocol
disk-based

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