How to count the frequency of words in a string using Linq with C#

1 Answer

0 votes
using System;
using System.Linq;
using System.Text.RegularExpressions;

class Program
{
    static void Main() {
        var str = "cshart java c c++ c c c c java c c java python go rust python php php";

        var matches = new Regex("[a-z-A-Z']+").Matches(str);
        var words = matches.Select(m => m.Value).ToList();
        
        Console.WriteLine(string.Join(", ", words));
        
        var result = words
                .GroupBy(m => m)
                .OrderByDescending(e => e.Count())
                .Select(w => new { word = w.Key, Count = w.Count() })
                .Take(15);

        foreach (var r in result) {
            Console.WriteLine($"{r.word}: {r.Count}");
        }
    }
}
 
 
 
 
/*
run:
 
cshart, java, c, c, c, c, c, c, java, c, c, java, python, go, rust, python, php, php
c: 8
java: 3
python: 2
php: 2
cshart: 1
go: 1
rust: 1
 
*/

 

 



answered Jul 5, 2023 by avibootz

Related questions

1 answer 119 views
1 answer 140 views
1 answer 132 views
1 answer 133 views
1 answer 120 views
...