Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,926 questions

51,859 answers

573 users

How to group words by first letter in C#

1 Answer

0 votes
using System;
using System.Collections.Generic;

class Program
{
    static void Main()
    {
        // List of words to group
        var words = new List<string>
        {
            "Python", "JavaScript", "C", "Java", "C#", "PHP",
            "C++", "Pascal", "SQL", "Rust"
        };

        var grouped = GroupByFirstLetter(words);

        // Print each group 
        foreach (var entry in grouped) {
            Console.WriteLine($"{entry.Key}: [{string.Join(", ", entry.Value)}]");
        }
    }

    /// <summary>
    /// Groups a list of words by their first letter.
    /// </summary>
    /// <param name="words">List of words to group</param>
    /// <returns>
    /// Dictionary where each key is a character and each value is a list of words.
    /// </returns>
    static Dictionary<char, List<string>> GroupByFirstLetter(List<string> words) {
        // Dictionary that maps a character to a list of words
        var groups = new Dictionary<char, List<string>>();

        // Loop through each word
        foreach (var word in words) {
            char firstLetter = word[0]; // Extract the first letter

            // If the key doesn't exist, create a new list
            if (!groups.ContainsKey(firstLetter)) {
                groups[firstLetter] = new List<string>();
            }

            // Add the word to the appropriate list
            groups[firstLetter].Add(word);
        }

        return groups;
    }
}


/*
run:

P: [Python, PHP, Pascal]
J: [JavaScript, Java]
C: [C, C#, C++]
S: [SQL]
R: [Rust]

*/


 



answered Jan 16 by avibootz
edited Jan 16 by avibootz
...