Project · Beginner

Word frequency

Normalize prepared text and count words with an explicit ordinal comparer.

All C# source files below are loaded together in the playground. Files written by a run live in its virtual directory.

Program.cs

using System;
using System.Linq;
using System.Collections.Generic;
using System.Globalization;
using System.Text;
using System.Text.Json;
using System.Threading;
using System.Threading.Tasks;

var text = "Rune code rune. Learn code, build rune.";
foreach (var pair in WordCounter.Count(text).OrderByDescending(x => x.Value).ThenBy(x => x.Key, StringComparer.Ordinal)) Console.WriteLine($"{pair.Key}:{pair.Value}");

Text/WordCounter.cs

using System;
using System.Collections.Generic;
public static class WordCounter
{
    public static Dictionary<string, int> Count(string text)
    {
        var counts = new Dictionary<string, int>(StringComparer.OrdinalIgnoreCase);
        foreach (var word in text.Split(new[] { ' ', '.', ',', '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries))
        {
            counts.TryGetValue(word, out var count);
            counts[word] = count + 1;
        }
        return counts;
    }
}

Wordfrequency.csproj

<Project Sdk="Microsoft.NET.Sdk">
  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>net9.0</TargetFramework>
    <ImplicitUsings>enable</ImplicitUsings>
    <Nullable>enable</Nullable>
  </PropertyGroup>
</Project>