Showing posts with label integer. Show all posts
Showing posts with label integer. Show all posts

Friday, July 5, 2013

Fetch maximum of an integer/ numeric/ decimal field of your table using Entity Framework

Whenever there is a need to fetch the maximum of integer/ numeric/ decimal field, you can execute following simple statement to get the same, if your project is using Entity Framework.

Following example is for finding maximum value in an Integer field. Similarly, you can use it for decimal/ double/ etc fields.

Also, consider "int?" (nullable) in below statement, because if there is no record in the particular table, then the below statement will return null. If you use "int" instead of "int?", then it will throw an exception if the table has no record.

int? intIdt = db.Users.Max(u => (int?)u.UserId);

Wednesday, April 11, 2012

Difference between integer Cast and Convert in C#

Technically speaking, Int64 and Long are equivalent in .NET
But if you convert one value into Int64, and cast the same value in Long the result is different.

Lets take one example:

(Long)27.5 returns 27
Whereas, Convert.ToInt64(27.5) returns 28
(Int64)27.5 returns 27

This is because, in C# (as well as in Java, and C++), the integer cast operation truncates - and so (Long)27.5 returns 27, whereas Convert has its own logic, and it rounds rather than truncating and so it returns 28.