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

Malik picture Malik · Aug 27, 2011 · Viewed 15.5k times · Source

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?

Answer

chrisaut picture chrisaut · Aug 27, 2011
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