Skip to content

Instantly share code, notes, and snippets.

@grishace
Last active June 30, 2020 13:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save grishace/997f767d6e60fafd6b79de113940bebd to your computer and use it in GitHub Desktop.
Save grishace/997f767d6e60fafd6b79de113940bebd to your computer and use it in GitHub Desktop.
Words frequency with LINQ
var str = "The quick brown fox jumped over the lazy dog. Hello-world! wOrLd WorLd. The new order!";
var words =
new Regex(@"\b([A-Z-]+)\b", RegexOptions.IgnoreCase)
.Matches(str)
.Select(m => m.Groups[0].Value.ToLower())
.GroupBy(g => g)
.Select(g => KeyValuePair.Create(g.Key, g.Count()))
.OrderByDescending(kv => kv.Value)
.ToDictionary(kv => kv.Key, kv => kv.Value);
private static readonly Regex word = new Regex(@"\b([a-z]+)\b", RegexOptions.IgnoreCase | RegexOptions.Compiled);
static void Main(string[] args)
{
File.ReadAllLines("WordFile.txt")
.SelectMany(s => word.Matches(s).Select(m => m.Groups[0].Value))
.GroupBy(w => w.ToLowerInvariant())
.Select(g => Tuple.Create(g.Key, g.Count()))
.OrderByDescending(t => t.Item2)
.Take(20)
.Select(t => t.Item1)
.ToList()
.ForEach(Console.WriteLine);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment