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