I have a sporting interest in how to make the next query more concise. And in general, understand how linq subqueries to a collection such as Dictionary are implemented.

Task:

To get from the Dictionary<int,int> collection Dictionary<int,int> element with the largest Value, if there are several elements with the maximum Value, then get everything. Then, from the resulting collection, if there are more than one elements, take the one with the smallest Key.

Because of my ignorance, I created such a monster, tell me how to make it nice and less verbose, it is advisable to fit everything into a single request, and not like mine.

 Dictionary<int,int> d = new Dictionary<int,int>(); var q1 = from a1 in d where a1.Value == d.Values.Max() select a1; var q2 = (from a2 in q1 where a2.Key == (from a3 in q1 select a3.Key).Min() select a2).First(); 

    1 answer 1

    It seems to be not a monster :):

     var result = d.OrderByDescending(n => n.Value).ThenBy(m => m.Key).First(); 

    Or as an option:

     var result = (from n in d orderby n.Value descending, n.Key select n).First(); 
    • Everything works, thank you. Only I do not understand how we get at least Key ? - Vasya Milovidov
    • one
      @VasyaMilovidov, we simply sort by two fields, by Value with decreasing ( descending ), by Key with increasing. And then we take the first value. - Mirdin
    • all ingenious is simple) thanks again) - Vasya Milovidov