我对 LINQ(在 C# 中)有疑问。我需要按字段对记录列表进行排序,该字段应该是 int
,但有时不是:
from MyObject obj in new MyObject()
where obj.Visibile=="1"
orderby Int32.Parse(obj.Order) ascending
select obj;
而且,正如我所说,如果 obj.Order 不是 int
,我会得到一个错误:System.FormatException: Input string was not in a correct format.
我想将非整数项目放在列表末尾,而不会出现任何错误。可能吗?
最佳答案
尝试使用 TryParse
int myInt;
from obj in MYobjects
where obj.Visibile=="1"
orderby (int.TryParse(Str, out myInt) ? myInt: 0 )
select obj;
或
MYobjects.OrderBy(r => Number(r.str);
//private function
int Number(string str)
{
int result_ignored;
if (int.TryParse(str,out result_ignored))
return result_ignored;
else
return 0;
}
关于c# - 按字段排序 (int)。如果字段不是int?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9189682/