Wesley Skeen
Wesley Skeen

Reputation: 1214

Separate list of strings into a new list depending on its first letter

I have a list of country names

Afghanistan
Albania
Bahamas, The
Bahrain
Cambodia
Cameroon
.
.
.

What I want to do is separate this list into other lists depending on the first letter.

So basically I want to have a list of countries that begin with a, b, c, ......

Upvotes: 0

Views: 154

Answers (2)

Justin Niessner
Justin Niessner

Reputation: 245419

So, you have a collection of strings. You can use LINQ to group them and convert them to a Dictionary.

First, you'll need to group them based on the first letter (in this situation, case matters so a and A will be treated differently) using GroupBy(n => n[0]) where n[0] gets the first character in the string.

Second, you'll want to convert the grouping to something that you can use an indexer with. A Dictionary would be perfect. Use ToDictionary(g => g.Key, g => g).

When you string it together, it'll look like:

var dict = names.GroupBy(n => n[0]).ToDictionary(g => g.Key, g => g);

And allow you to get the grouped names using:

foreach(var n in dict['A'])
{
    // Print out each country starting with 'A'
    Console.WriteLine(n);
}

Upvotes: 6

xeraphim
xeraphim

Reputation: 4645

You can do it like this:

var countriesWithStartingLetterA = countries.Where(x => x.StartsWith("A")).ToList();

Upvotes: 0

Related Questions