Simple file content summary

A few days ago, I was reviewing some old samples to teach C# and I came across one that instructed the user to write a simple program. The goal was to read a text file and display on the Console a small summary containing, for example, the number of characters and the number of lines. The solution provided for this exercise was to iterate over the content of the file character by character and increment a few counters based of Char.IsSomething tests.

Here is a much cooler way to do that using a LINQ query :
string content = File.ReadAllText(path);

var contentByGroups =
from c in content
group c by Char.GetUnicodeCategory(c) into groups
select new { Category = groups.Key,
Count = groups.Count() };

foreach (var group in contentByGroups)
{
Console.WriteLine("Category {0} : {1}",
group.Category,
group.Count);
}


The Char.GetUnicodeCategory is used to get the corresponding category of each character of the file.

Popular posts from this blog

Handling exceptions the right way in WCF (part 2)

Adding a delay before processing Textbox events

Change the deployment URL of a ClickOnce application