c# - 按字段排序 (int)。如果字段不是int?

标签 c# linq int

我对 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/

相关文章:

c# - 放大或缩小时如何使 Canvas 区域在 ScrollViewer 中居中,而不是所有内容都可以显示在查看窗口中

c# - 如何使用 ADO.NET 从具有一对多关系的 DAL 层中的多个表返回数据

c# - 访问虚拟机网络服务

c - 在数组 c 中找到所有可能的对

c# - 列值不能重复

c# - 使用 Linq to SQL 通过合并两个整数字段来创建唯一的数字列表

Linq 由多列区分并选择最新行

c# - 根据组数对列表进行排序

c - 在用 C 编写一个简单的程序时遇到问题,有什么建议吗?

java - 原始类型int实际上如何转换为String?