I’ve got this problem, I have a table for purchases
Purchases(Date DateTime, Number string)
I want is to create a new record, so I need the Max(Number), the problem here is that Number is a string, I’ve tried
Purchases.Select(X=>int.Parse(X.Number)).Max()
but it could throw an exception, I’ve create a custom ToInt() extension so when I use
Purchases.Select(X=>X.Number.ToInt()).Max()
it throws an exception saying that my ToInt() can’t be used with linq query same as the famous ToString()
so my question is : is there a way to cast a string to int in linq query & handling exceptions at the same time or to integrate custom functions to a linq query !!
and this’s my extension
public static int ToInt(this string s)
{
try
{
return int.Parse(s);
}
catch
{
}
return 0;
}
First way:
Second way:
The key is the
.ToList()in those two ways. It gets all thestringdata from the database, so when you callint.TryParseon the results, the database query has already been run, so it is using pure CLR code, and not trying to convertint.TryParseinto a SQL query. I made an EF context in one of my Sandbox projects and verified this works.