开发者

How can I do a "Group by" with a Dictionary object?

开发者 https://www.devze.com 2023-02-15 20:44 出处:网络
In C#, I have a Dictionary object which stores one integer value and one decimal value. Dictionar开发者_JS百科y<decimal,int> objDict = new Dictionary<decimal,int>();

In C#, I have a Dictionary object which stores one integer value and one decimal value.

Dictionar开发者_JS百科y<decimal,int> objDict = new Dictionary<decimal,int>();

and the values are

   12  1
   23  1
   14  1
   6   2
   9   2
   16  3
   -4  3

I want to do a group by on this using LINQ, so that I will get the max value. The expected output is

   23  1
    9  2
   16  3

How to do that?


var query = yourDictionary.GroupBy(x => x.Value,
                                   (k, g) => new {
                                                     Max = g.Max(x => x.Key),
                                                     Value = k
                                                 });


var itemCount2NumberMap = yourDictionary.GroupBy(item=>item.Value).ToDictionary(x=>x.Key, x=>x.Max(y=>y.Key));
0

精彩评论

暂无评论...
验证码 换一张
取 消