Top Words with LINQ
csharpC# and .NETbeginnerinterview-prep
Count word frequency, ignoring case, and take the five most common.
string text = "the cat and the hat and the bat the end";
var topWords = text
.Split(new[] { ' ', '\n', '\t' }, StringSplitOptions.RemoveEmptyEntries)
.GroupBy(word => word.ToLowerInvariant())
.Select(g => new { Word = g.Key, Count = g.Count() })
.OrderByDescending(x => x.Count)
.ThenBy(x => x.Word)
.Take(5);
foreach (var item in topWords)
{
Console.WriteLine($"{item.Word}: {item.Count}");
}