Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

linq

I have the following code, I am trying to get the strings which starts with capital, but I don't know how! without linq I can do it but inside LINQ... no idea!

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;
}
like image 687
Saeid Yazdani Avatar asked Dec 18 '11 01:12

Saeid Yazdani


People also ask

How do you check if a string starts with a capital letter C#?

IsUpper(String, Int32) Method. This method is used to check whether the specified string at specified position matches with any uppercase letter or not. If it matches then it returns True otherwise returns False.

How would you check if each word in a string begins with a capital letter in Python?

How would you check if each word in a string begins with a capital letter? The istitle() function checks if each word is capitalized.

Can you use Linq on a string?

LINQ can be used to query and transform strings and collections of strings. It can be especially useful with semi-structured data in text files. LINQ queries can be combined with traditional string functions and regular expressions. For example, you can use the String.


2 Answers

The earlier solutions here all assume queryValues2 consists of strings with at least one character in them. While that is true of the example code, it isn't necessarily always true.

Suppose, instead, you have this:

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

(which might be the case if the string array is passed in by a caller, for example).

A solution that goes straight for qRes[0] will raise an IndexOutOfRangeException on the "" and a NullReferenceException on the null.

Therefore, a safer alternative for the general case would be to use this:

where !string.IsNullOrEmpty(qRes) && char.IsUpper(qRes[0])
like image 65
Matthew Strawbridge Avatar answered Sep 28 '22 02:09

Matthew Strawbridge


Try this:

where char.IsUpper(qRes[0])
like image 36
slugster Avatar answered Sep 28 '22 00:09

slugster