2

我有一个代码:

string[] sizes = new string[] {"1","11","2","22","200","222", null, "105", "101", "102", "103", "90" };

try
{
  var size = from x in sizes
           orderby x.Length, x
           select x;

  foreach (var p in size)
  {
     Console.WriteLine(p);
  }
   Console.Read();
}
catch (NullReferenceException)
{
}

如何在 x.Length 中捕获 null,并继续执行代码?

4

2 回答 2

11

如何在 x.Lenght 中捕获 null 并继续执行代码?

那么,在这种情况下,您希望值是多少?例如,您可以使用:

orderby x == null ? -1 : x.Length, x

或者可能:

orderby x == null ? int.MaxValue : x.Length, x

或者可能:

orderby x == (x ?? "").Length, x

或者,也许您应该过滤字符串以开始:

var size = from x in sizes
           where x != null
           orderby x.Length, x
           select x;
于 2012-08-10T10:27:55.063 回答
1

你应该尝试添加

where x != null

在您的过滤中

于 2012-08-10T10:30:44.693 回答