Monday, May 27, 2013

How to handle null value returned when using Linq to get Max Value for a column

Very often we use Select query to get Max value for a column in Ado.net like
 SELECT MAX(UnitPrice) FROM products
. We can do the same thing in Linq but what about if we donot have any row to return.In sich a case you will probably rest up in getting casting error "Unable to convert null to specific type".
How to handle such situations in Linq
.net framework provides nullable type Nullable types are instances of the System.Nullable struct. A nullable type can represent the normal range of values for its underlying value type, plus an additional null value.
Now if we write the same query in Linq
int? query = (from o in context.Products select (int?)o.UnitPrice).Max(); 
This query will result in null value.We can cast this null value into our requested datatype Convert.ToInt32(query);

No comments :

Post a Comment