Search code examples
c#linqletters

Linq query - find strings based upon first letter b/w two ranges


We have a list containing names of countries. We need to find names of countries from list b/w two letters. Like names of all countries with name starting b/w A-G and so on. We create following linq query but its ugly.

var countryAG = from elements in countryList
where elements.StartsWith("A") || 
elements.StartsWith("B") || 
elements.StartsWith("C") || 
elements.StartsWith("D") || 
elements.StartsWith("E") || 
elements.StartsWith("F") || 
elements.StartsWith("G") || 
elements.StartsWith("H") 
select elements;

where countryList is created in C#

List< string> countryList = new List< string>();

Any help or any other efficient way to accomplish above task?


Solution

  • var countryAG = from elements in countryList
                    where elements[0] >= 'A' && elements[0] <= 'H'
                    select elements;
    

    Chars are just numbers really, thus you can compare them as such