'How to find the highest value in a Dictionary, as well as all the keys that map to it? [duplicate]
For example,
This is my dictionary, mydict
key value 1 1500 2 1900 3 1760 4 1800 5 1460
It should return the maximum value (1900), and the key (2)
But for this:
key value 1 1500 2 1900 3 1760 4 1900 5 1460
It should return maximum value 1900, and the keys (2, 4)
How should I be doing this? Is System.Linq helpful?
Solution 1:[1]
Welcome to the stack overflow!!
Here is an example as per your question:
Dictionary<int, int> keyValuePairs = new Dictionary<int, int>();
keyValuePairs.Add(1, 1500);
keyValuePairs.Add(2, 1900);
keyValuePairs.Add(3, 1760);
keyValuePairs.Add(4, 1900);
keyValuePairs.Add(5, 1460);
int maxValue=keyValuePairs.Values.Max();
var maxResult = keyValuePairs.Where(x => x.Value == maxValue).Select(x => new { x.Key, x.Value }).ToList();
foreach (var item in maxResult)
{
Console.WriteLine("Key: {0} Value: {1}", item.Key, item.Value);
}
Output
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |

