I have a Dictionary of type
Dictionary<int, GValue>
where GValue is an object that contains two double values P1 and P2
I am trying to get key for maximum values from dictinary using follwing code
var keyForMaxP1 = dict.Keys.Aggregate((i, j) => dict[i].P1 >= dict[j].P1 ? i : j);
var keyForMaxP2 = dict.Keys.Aggregate((i, j) => dict[i].P2 >= dict[j].P2 ? i : j);
It gives me keys for max P1 and P2 Correctly.
But what if dictinary contains more than one key with max P1 Or P2 Value ?? Here it still returning one Key which comes first during traversing of dictinary.
Edit
Suppose dictionary have values P1 with max value say 3.52. Now if there are two entries in dictionary with value P1 = 3.52, I wanna to get both the keys related to this value
If you want all KeyValuPairs with a max-value you can use Enumerable.GroupBy:
var MaxP1KeyValues = dict.GroupBy(kv => kv.Value.P1)
.OrderByDescending(g => g.Key).First();
var MaxP2KeyValues = dict.GroupBy(kv => kv.Value.P2)
.OrderByDescending(g => g.Key).First();
foreach (var kv in MaxP1KeyValues)
{
Console.WriteLine("Key:{0} Value-P1:{1}", kv.Key, kv.Value.P1);
}
foreach (var kv in MaxP2KeyValues)
{
Console.WriteLine("Key:{0} Value-P2:{1}", kv.Key, kv.Value.P2);
}
This groups all KeyValuePair<int, GValue> in the dictionary by the value of P1/P2, the OrderByDescending + First selects the group with the highest values.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With