I suppose you have a class similar to this:
class TblSatarProduct
{
public int Id_Product {get;set;}
public int star {get;set;}
}
And tbl_satar_Product
is a instance of this. Now you can do this in your method public int StarProduct(int id_Product)
:
First get list (IEnumerable
):
var list = db
.tbl_satar_Product
.Where(p => p.Id_Product == id_Product)
if (list == null)
{
return 0; // or default value
}
If star
is int
you don't need && p.star != null
, if you need check if have a value in star
, maybe you need to change it to int?
in this case you could use != null
.
Then, you get the average:
double average = list.Average(s => s.star);
if (average == null)
{
return 0; // or default value
}
Maybe in this point, you can return double
type, and then who call method StarProduct
will have to take care of the conversion.
Finally:
try {
int averageInt = Convert.ToInt32(average);
return averageInt;
}
catch (OverflowException ex)
{
//outside the range of the Int32 type
//check what do you do?
}
Info
Enumerable.Average (Método) (IEnumerable)
Casting and Type Conversions (C# Programming Guide)