C# LINQ, Summation and Type system - What is the int? type
I'm doing work with LINQ in C#. Part of the code requires a Sum down a column.
SomeTable.Where( CONDITION ).Sum( Entity => Entity.IntColumn );
This returns a type of int? rather than an int as the table's column's type is also of the int? form.
My questions are thus:
What is the int? or double? e&. type? - What is the best practice for co开发者_JS百科nverting or casting those types into their useable int or double e&. counter parts?int?
is shorthand for Nullable<int>
http://msdn.microsoft.com/en-us/library/1t3y8s4s%28v=VS.80%29.aspx
You can use myInt.HasValue
to see if there is a value set or if it is null and then myInt.Value
to retrieve the int when it is not null.
int?, double?, etc are nullable types. Nullable types can represent all the values of an underlying type, and an additional null value.
Each instance of a nullable type has two public read-only properties:
HasValue
HasValue is of type bool. It is set to true when the variable contains a non-null value.
Value
Value is of the same type as the underlying type. If HasValue is true, Value contains a meaningful value. If HasValue is false, accessing Value will throw a InvalidOperationException.
int? x = 10;
if (x.HasValue)
{
System.Console.WriteLine(x.Value);
}
else
{
System.Console.WriteLine("Undefined");
}
http://msdn.microsoft.com/en-us/library/2cf62fcy.aspx#Y431
You have to select one column of a numeric type:
SomeTable.Where( CONDITION ).Sum(Entity => Entity.NumericColumn);
Then the sum will be of that numeric type.
精彩评论