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

GraphicsPath using RotateAt drawing with GDI+
Converting program with C and asm code to a DLL
Override method of dll
How to play a sound through Webcamera using c#? [closed]
SQL COALESCE vs. DBNull check in C#
How to read data from excel like a database table and also update the data on a query based in using VSTO in C#.net?
asp.net-mvc's ROUTE: The resource cannot be found
Get an error if opening file again
how to check content-type/application text in c#
Removing the Object Moved HTML in the body on a Response.Redirect
c# .net 4.5 async / multithread?
how to get progress report from ThreadPool.QueueUserWorkItem
Dynamic Right-Click Menu C# Based on Location
access html elements using class name in JavaScript
Redirect URI Error On Valid Login ASP.NET
EF 4.1 Nested Complex type to single field

Categories

HOME
indexing
ftp
liquibase
jquery-plugins
cryengine
install
virtualhost
sitemap
box-api
soap-client
google-search-appliance
fine-uploader
klipfolio
policy
dynamics-ax-2012-r3
concrete5
opencsv
log4net-configuration
apache-falcon
respect-validation
azure-web-roles
google-chrome-console
weld
ocamlbuild
spring-ide
easyquery
g77
cloudconvert
hellosign
bipartite
group
esprima
ownership
ldd
django-taggit
aws-kms
salesforce-service-cloud
ideavim
alchemy
skscene
gnu-sort
ruby-1.8.7
commercetools
event-tracking
libgcrypt
play-json
transbase
consul-template
borland-c++
eula
clearquest
ultraedit
maven-archetype
bungeecord
mri
quickfixn
unityvs
growl
scjp
kernel-density
carrier
complete
myrrix
leap-year
asp.net-4.0
uikit-dynamics
removeall
http-compression
exi
windows-scheduler
pudb
feincms
linear-interpolation
wxperl
project-files
quazip
azure-appfabric
chars
carbon-emacs
dynamic-scope
authkit
projectgen
onresize

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