Convert string to int in linq Entity Framework query and parse exception handling

I have this problem, I have a shopping table

Purchases(Date DateTime, Number string) 

I want to create a new record, so I need Max (Number), the problem is that Number is a string , I tried

 Purchases.Select(X=>int.Parse(X.Number)).Max() 

but this may throw an exception, I create a custom ToInt() extension, so when I use

 Purchases.Select(X=>X.Number.ToInt()).Max() 

it throws an exception saying that my ToInt () cannot be used with linq request in the same way as the famous ToString ()

so my question is : is there a way to pass a string to int in a linq query and handle the exceptions at the same time or integrate user-defined functions into a linq query !!

and this is my extension

  public static int ToInt(this string s) { try { return int.Parse(s); } catch { } return 0; } 
+6
source share
2 answers

First way:

 var numbers = Purchases.Select(x => x.Number).ToList(); int temp; int max = numbers.Select(n => int.TryParse(n, out temp) ? temp : 0).Max(); Console.WriteLine("Max: {0}", max); 

The second way:

 int temp2; int max2 = Purchases.Select(x => x.Number).ToList().Select(n => int.TryParse(n, out temp2) ? temp2 : 0).Max(); Console.WriteLine("Max 2: {0}", max2); 

The key is .ToList() two ways. It gets all the string data from the database, so when you call int.TryParse in the results, the database query is already running, so it uses pure CLR code and does not try to convert int.TryParse to SQL query. I created an EF context in one of my Sandbox projects and confirmed that it works.

+10
source

I don’t understand why you don’t want an exception, because if you didn’t perform the casting, then something happened with your application (or at least that’s how I got it). I also do not understand why save what should be a number as a string in the database. Usually you will store it as a number, so you won’t have to solve such problems later, and if someone tries to insert the wrong value, you cannot insert it.

BUT. If you want this line to work, you should use int.TryParse , which will return you true if the value is successful and the value will be placed in the 'out' element that will be outside the request. eg:

 int tmp; Purchases.Select(X=>int.TryParse(X.Number, out tmp) ? tmp : 0).Max() 

and instead of "0" enter a default value that will not work with your logic.

+2
source

Source: https://habr.com/ru/post/926683/


All Articles