Sort words by letter count in C#

[letter count]

This example sorts words by letter count. It counts the number of distinct letters in a list of words and displays the words and their counts sorted by the counts. The program is remarkably simple.


The following code shows how the program builds and displays the letter count list.

// Find and display the words and counts.
private void Form1_Load(object sender, EventArgs e)
{
    string[] words = {
        "Alabama",
        "Alaska",
        ...
        "Wyoming"
    };

    // Get a list holding each word's unique letter count and name.
    var count_query =
        from string word in words
        orderby word.ToCharArray().Distinct().Count()
        select word.ToCharArray().Distinct().Count() + ", " + word;
    lstLetterCounts.DataSource = count_query.ToArray();
}

The code first defines an array of words. It then builds the LINQ query that does most of the work.

The query loops through the words in the array. For each word, it calls the string class’s ToCharArray method to convert the word into an array of characters. It then calls Distinct to get the distinct letters in the array. Finally it calls Count to see how many distinct letters there are. It uses the orderby clause to order the results by this value.

The query selects the same letter count, plus a comma, plus the original word. The result is that the query returns strings holding each word’s distinct letter count and the word.

To display the results, the code simply calls the query’s ToArray method to convert the IEnumerable list of strings into an array. It then sets the ListBox control’s DataSource property equal to the resulting array and the ListBox displays the strings.


Download Example   Follow me on Twitter   RSS feed   Donate




This entry was posted in algorithms, LINQ, mathematics and tagged , , , , , , , , , , , . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *