Order by a field (int). If the field it is not int?

前端 未结 3 1793
执念已碎
执念已碎 2021-01-25 19:44

I have a problem with LINQ (in C#). I need to order a list of records by a field, which should be int, but sometimes not :

from MyObject obj in new          


        
3条回答
  •  攒了一身酷
    2021-01-25 20:06

    Try by maming use of TryParse

    int myInt;                
    from obj in MYobjects
             where obj.Visibile=="1" 
             orderby  (int.TryParse(Str, out myInt) ?  myInt: 0 )
             select obj;
    

    OR

    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;
     }
    

提交回复
热议问题