BLOG.CSHARPHELPER.COM: Use LINQ to order a list of words by the number of distinct letters they contain in C#
Use LINQ to order a list of words by the number of distinct letters they contain in C#
This example counts the number of distinct letters in a list of words and displays the words and their counts sorted by the counts. The code is remarkably simple. The following shows the code that the program uses to build and display the 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 ToCharArray to convert the word into an array of characters, calls Distinct to get the distinct letters in the array, and 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 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 and sets the ListBox's DataSource property equal to the result.
Comments