Linq query - search for strings based on the first letter b / w of two ranges

We have a list containing country names. We need to find the names of countries from the b / w list of two letters. Like the names of all countries with a name starting b / w AG and so on. We create the 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 effective way to accomplish the above task?

+4
source share
6 answers
 var countryAG = from elements in countryList where elements[0] >= 'A' && elements[0] <= 'H' select elements; 

Balls are just numbers, so you can compare them as such

+10
source

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 .

+2
source

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

 countryList.Where((s) => s[0] <= 'A' && s[0] >= 'G'); 
+2
source

You can use the prefix list and then use the prefix list for comparison - this way you can easily use different prefix lists depending on which 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))); 
+1
source

Try using this code:

 var start = "a"; var end = "g"; var regex = new Regex(string.Format("^[{0}-{1}]", start, end)); var result = list.Where(x => regex.Match(x.ToLowerInvariant()).Success); 

'start' and 'end' are static as an example.

+1
source

I have two extension functions:

 public static IEnumerable<char> Range(char start, char end) { return Enumerable.Range((int)start, (int)end - (int)start + 1).Select(i => (char)i); } 

which creates a range of characters, and

 public static bool In(this string source, IEnumerable<string> collection) { return collection.Contains(source); } 

which is just the opposite of Contains , mainly for readability.

Together I can do:

where elements[0].In(Range('a', 'f')))

0
source

Source: https://habr.com/ru/post/1369314/


All Articles