Friends I have created a dictionary. For getting top 2 elements I am using below code.
topKeys[B] = (from entry in differentKeys orderby entry.Value descending
select entry)
.ToDictionary(pair => pair.Key, pair => pair.Value).Take(2)
.ToDictionary(x=>x.Key,x=>x.Value).Values.ToArray();
But it seems not working. Can you please suggest line in C# which will return me top 2 maximum elements? differentKeys is name of my dictionary. Check the snaps below...
It's not clear why you keep converting to dictionaries all the time. The order of entries Dictionary<,>
is not guaranteed.
It looks like you just want:
var topValues = differentKeys.Values
.OrderByDescending(x => x)
.Take(2)
.ToArray();
Or if you want the keys which correspond to the top values:
var keysForTopValues = differentKeys.OrderByDescending(x => x.Value)
.Select(x => x.Key)
.Take(2)
.ToArray();
See more on this question at Stackoverflow