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

2019-03-01 09:59发布

问题:

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 MyObject()
where obj.Visibile=="1"
orderby Int32.Parse(obj.Order) ascending
select obj;

and, as I said, if obj.Order is it not int, I get an error : System.FormatException: Input string was not in a correct format.

I'd like to put the non-int items at the end of the list, without get any error. Is it possible?

回答1:

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


回答2:

Do not use Int32.Parse, but use a method you create yourself that uses Int32.TryParse to try to parse the int. If it succeeds, return the number found, if it fails return Int32.MaxValue to get that at the end.

from MyObject obj in new MyObject()
where obj.Visibile=="1"
orderby TryParse(obj.Order) ascending
select obj;


public int TryParse(string value)
{
  int val;
  if (Int32.TryParse(value, out val))
      return val;

  return Int32.MaxValue;
}


回答3:

If it is possible try adding a column in database IsInteger which stores if the order is integer or not at time of Insert.

So, it will be easy to get and sort integer and non-integer orders.



标签: c# linq order int