次のようなクラスがあるとします。
class TblSatarProduct
{
public int Id_Product {get;set;}
public int star {get;set;}
}
そしてtbl_satar_Product
、これの例です。これで、メソッドでこれを行うことができますpublic int StarProduct(int id_Product)
:
最初にリストを取得 ( IEnumerable
):
var list = db
.tbl_satar_Product
.Where(p => p.Id_Product == id_Product)
if (list == null)
{
return 0; // or default value
}
star
がint
必要ない場合、&& p.star != null
に値があるかどうかを確認する必要がある場合は、この場合はstar
に変更する必要があるかもしれません。int?
!= null
次に、平均を取得します。
double average = list.Average(s => s.star);
if (average == null)
{
return 0; // or default value
}
おそらくこの時点で、型を返すことができます。double
その後、メソッドを呼び出す人StarProduct
が変換を処理する必要があります。
ついに:
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 (メソッド) (IEnumerable)
キャストと型変換 (C# プログラミング ガイド)