当我将 String.Split
与随机字符串一起使用时,我遇到了这个异常。
List<string> linhas = new List<string>();
linhas.Add("123;abc");
linhas.Add("456;def");
linhas.Add("789;ghi");
linhas.Add("chocolate");
var novas = linhas.Where(l => l.ToString().Split(';')[1]=="def");
最佳答案
最后一个字符串 "chocolate"
不包含 ";"
,因此 String.Split
返回一个包含单个字符串的数组“巧克力”
。这就是如果您尝试访问第二个时会出现异常的原因。
你可以使用 ElementAtOrDefault
它为字符串返回 null
:
var novas = linhas.Where(l => l.Split(';').ElementAtOrDefault(1) == "def");
使用匿名类型的更长方法:
var novas = linhas
.Select(l => new { Line = l, Split = l.Split(';') })
.Where(x => x.Split.Length >= 2 && x.Split[1] == "def")
.Select(x => x.Line);
关于c# - 如何在 LINQ WHERE 中防止 System.IndexOutOfRangeException?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34948958/