所有使用 C#7 或更新版本的人滚动到底部,其他人都可以阅读原始答案:
是的,如果您将正确的参数传递给int.TryParse,您可以。两个重载都将int 作为out 参数,并在内部使用解析后的值对其进行初始化。像这样:
int note;
Documenti = Documenti
.OrderBy(o => string.IsNullOrEmpty(o.Note))
.ThenBy(o => Int32.TryParse(o.Note, out note))
.ToList();
clean 方法使用解析为int 并在无法解析时返回int? 的方法:
public static int? TryGetInt(this string item)
{
int i;
bool success = int.TryParse(item, out i);
return success ? (int?)i : (int?)null;
}
现在你可以使用这个查询(OrderByDescending 因为true 比false“更大”):
Documenti = Documenti.OrderByDescending(d => d.Note.TryGetInt().HasValue).ToList();
这比使用int.TryParse 中使用的局部变量作为输出参数更简洁。
Eric Lippert 评论了我的另一个答案,他举了一个可能会伤害的例子:
C# LINQ: How is string("[1, 2, 3]") parsed as an array?
更新,this has changed with C#7。现在可以在使用out参数的地方直接声明变量:
Documenti = Documenti
.OrderBy(o => string.IsNullOrEmpty(o.Note))
.ThenBy(o => Int32.TryParse(o.Note, out int note))
.ToList();