0

I have a Dictionary<char, int> charstat to count occurrences of a character. I want to get the 5 most common character counts from this dictionary. How do go about doing this.

Some example data:

 <'T', 1>
 <'A', 2>
 <'C', 5>
 <'Q', 10>
 <'B', 3>
 <'Z', 7>

And from this I want to get in order of the largest count:

Q
Z
C
B
A
Jamie Dixon
  • 53,019
  • 19
  • 125
  • 162
fotg
  • 639
  • 1
  • 12
  • 25

2 Answers2

5

I want to get the 5 most common character counts from this dictionary.

var item = charstat.OrderByDescending(r => r.Value)
                          .Select(r => r.Key)
                          .Take(5);
Habib
  • 219,104
  • 29
  • 407
  • 436
  • @Rawling Before editing code in question was invalid that was making this solution invalid as well. That might be a reason. +1 from me anyway. – Leri Jun 07 '13 at 07:36
  • 1
    @PLB, I didn't have `Select` clause, so it was originally selecting the dictionary item. now edited it to select the key. – Habib Jun 07 '13 at 07:42
  • Of course, if there's a tie, i.e. some values are equal, it is undefined which order these come in. – Jeppe Stig Nielsen Jun 07 '13 at 07:53
2
  Dictionary<char, int> dir = new Dictionary<char, int>();
  // ...
  var query = (from p in dir
              orderby p.Value descending
              select p).Take(5);
  foreach (var item in query) {
    Console.Out.WriteLine("Char: {0}, Count: {1}", item.Key, item.Value);
  }
Ondrej Svejdar
  • 21,349
  • 5
  • 54
  • 89