Linq Dictionary question

  • Thread starter Thread starter Eps
  • Start date Start date
E

Eps

Hi there,

Say I have a dictionary of the type...

Dictionary<Color, int>

how would I get the 5 key value pairs with the greatest value (the value
being the integer).

It should be simple but I have been struggling to do it in Linq, any
examples would be much appreciated.

Regards.
 
Hi there,

Say I have a dictionary of the type...

Dictionary<Color, int>

how would I get the 5 key value pairs with the greatest value (the value
being the integer).

Dictionary<Color, int> dict;
...
IEnumerable<KeyValuePair<Color, Int>> result =
dict.OrderByDescending(pair => pair.Value).Take(5);
 
Pavel said:
Dictionary<Color, int> dict;
...
IEnumerable<KeyValuePair<Color, Int>> result =
dict.OrderByDescending(pair => pair.Value).Take(5);

ok I new it would be simple :)

what happens if there are less then five kvp's in the dictionary, is
there an exception thrown ?, I guess I should check the number of items
anyway right ?.

thanks.
 
ok I new it would be simple :)

what happens if there are less then five kvp's in the dictionary, is
there an exception thrown ?

No - it will just give you all the items (in descending order). All
Take() does is limit the *maximum* number of elements returned.
I guess I should check the number of items anyway right ?.

Well, that depends on what you're doing with it.

Jon
 
Back
Top