// Collection of code snippets by Arne Vajhøj // (likely posted to comp.os.vms/INFO-VAX, INFO-TPU, MACRO32, eksperten.dk, newz.dk, LinkedIn or other place sometime between 1990 and now) using System; using System.Collections.Generic; public class WordCount : IComparable { string word; int count; public WordCount(string word) { this.word = word; this.count = 1; } public string Word { get { return word; } } public int Count { get { return count; } } public void Increment() { count++; } public int CompareTo(object o) { return ((WordCount)o).Count - count; } } public class WordCountList { private Dictionary list; private int minlen; public WordCountList(int minlen) { this.list = new Dictionary(); this.minlen = minlen; } public void AddWord(string word) { if(word.Length >= minlen) { if(list.ContainsKey(word)) { list[word].Increment(); } else { list.Add(word, new WordCount(word)); } } } public void AddText(string text) { string[] words = text.Split(" ".ToCharArray()); for(int i = 0; i < words.Length; i++) { AddWord(words[i]); } } public ICollection GetTop(int n) { List temp = new List(); temp.AddRange(list.Values); temp.Sort(); temp.RemoveRange(n, temp.Count - n); return temp; } } public class TestClass { public static void Test(string s) { WordCountList proc = new WordCountList(1); proc.AddText(s); ICollection top = proc.GetTop(3); foreach(WordCount wc in top) { Console.WriteLine(wc.Word + " : " + wc.Count); } } public static void Main(string[] args) { Test(@"Dette er en lille test - er en en"); Console.ReadLine(); } }