How to check if a string starts with a capital letter in a LINQ query

I have the following code, I am trying to get lines starting with capital, but I don’t know how! without linq, I can do it, but inside LINQ ... I don’t know!

string[] queryValues1 = new string[10] {"zero", "one", "two", "three", "four", "five", "six", "seven","nine", "ten" }; string[] queryValues2 = new string[3] { "A", "b", "c" }; var queryResult = from qResult in queryValues1 from qRes in queryValues2 where qResult.Length > 3 where qResult.Length < 5 where qRes[0].StartWithCapital //how to check if qRes started with a capital letter? select qResult + "\t" + qRes + Environment.NewLine; foreach (var qResult in queryResult) { textBox1.Text += qResult; } 
+6
source share
6 answers

Previous solutions, which everyone here suggests, queryValues2 consists of strings with at least one character in them. Although this is true for example code, this is not always always true.

Suppose you have this:

 string[] queryValues2 = new string[5] { "A", "b", "c", "", null }; 

(what could be if the array of strings is transmitted by the caller, for example).

A solution that goes directly to qRes[0] will raise IndexOutOfRangeException by "" and a NullReferenceException by null .

Therefore, a safer alternative for the general case would be the following:

 where !string.IsNullOrEmpty(qRes) && char.IsUpper(qRes[0]) 
+8
source

Try the following:

 where char.IsUpper(qRes[0]) 
+6
source

Check out Char.IsUpper(qRes[0]) .

+3
source
 where Char.IsUpper(qRes.FirstOrdefault()) 

This is the same as outside of LINQ.

+1
source

try something like this (in this code, arr is the string []):

 from a in arr where ((int)a.ToCharArray()[0] >= 65 && (int)a.ToCharArray()[0] <= 90) select a 

The bottom line is to check if the first ASCII character is in the range of capital letters or not.

0
source
  static void Main(string[] args) { Console.Write("\nLINQ : Find the uppercase words in a string : "); Console.Write("\n----------------------------------------------\n"); string strNew; Console.Write("Input the string : "); strNew = Console.ReadLine(); //string[] newStr = strNew.Split(' '); var ucWord = WordFilt(strNew); Console.Write("\nThe UPPER CASE words are :\n "); foreach (string strRet in ucWord) { Console.WriteLine(strRet); } Console.ReadLine(); } static IEnumerable<string> WordFilt(string mystr) { var upWord = mystr.Split(' ') .Where(x=> !string.IsNullOrEmpty(x) && char.IsUpper(x[0])); return upWord; } 
0
source

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


All Articles