Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

linq

letters

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?

like image 378
Malik Avatar asked Aug 27 '11 19:08

Malik


4 Answers

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

like image 106
chrisaut Avatar answered Oct 12 '22 23:10

chrisaut


I can't test it right now, but I would try

countryList.Where((s) => s[0] <= 'A' && s[0] >= 'G');
like image 28
Nick Babcock Avatar answered Oct 12 '22 23:10

Nick Babcock


You could use a prefix list and then use the prefix list for comparison - this way you can easily use different prefix lists based on what range you are interested in:

 List<string> prefixList = new List<string>() { "A", "B", "C", "D", "E", "F", "G" };
 var countryAG = countryList.Where( x=> prefixList.Any( p => x.StartsWith(p)));
like image 36
BrokenGlass Avatar answered Oct 12 '22 23:10

BrokenGlass


Try

char[] startingLetters = new char[] {'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H'};
var countryAG = 
    from elements in countryList 
    where elements.IndexOfAny(startingLetters, 0, 1) == 0 
    select elements;

See here for information on IndexOfAny.

like image 34
Yahia Avatar answered Oct 12 '22 23:10

Yahia