我有以下代码,我试图获得以资本开头的字符串,但我不知道如何!没有linq我可以做但在LINQ里面......不知道!
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;
}
Run Code Online (Sandbox Code Playgroud)
这里的早期解决方案都假设queryValues2
包含至少包含一个字符的字符串.虽然示例代码也是如此,但并不总是如此.
相反,假设你有这个:
string[] queryValues2 = new string[5] { "A", "b", "c", "", null };
Run Code Online (Sandbox Code Playgroud)
(例如,如果字符串数组由调用者传入,则可能是这种情况).
这会直接的解决方案qRes[0]
将引发IndexOutOfRangeException
对""
与NullReferenceException
上null
.
因此,对于一般情况,更安全的替代方案是使用此:
where !string.IsNullOrEmpty(qRes) && char.IsUpper(qRes[0])
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
10305 次 |
最近记录: |