First, have a look at this code:
Dictionary<int,int> dict = Dictionary<int,int>();
dict[3] = 1;
dict[2] = 2;
dict[1] = 3;
foreach(KeyValuePair<int,int> item in dict.OrderByDescending(p => p.Value))
{
print(item.Value);
break;
}
This code, basically prints the value of the entry in the dictionary with the highest value. I’d like to accomplish this without using a “broken” foreach loop. How might I do that?
Well, you could do:
This is not only more concise, but also doesn’t require sorting the dictionary out-of-place first (which is what starting an enumeration on
OrderByDescendingdoes), so is more efficient in both time and space.If you need the key as well, you can use a
MaxByoperator (such as from moreLinq) as follows:It is possible to accomplish this with standard LINQ to Objects in
O(n)time andO(1)space with theAggregateoperator, but it’s quite ugly: