0

我的数据库中有两张图片详细信息和图片喜欢的表格。

public partial class picturedetail
{
    public int idpictures { get; set; }
    public int iduser { get; set; }
    public string picTitle { get; set; }
    public string picFilename { get; set; }
    public System.DateTime pictime { get; set; }
    public int likes { get; set; }
    public int nuditylevel { get; set; }
    public int fakeslevel { get; set; }
}

  public partial class picturelike
{
    public int idpicturelike { get; set; }
    public int idpictures { get; set; }
    public int iduser { get; set; }
    public System.DateTime iddatetime { get; set; }
    public int iduserlikedby { get; set; }
    public int likenumber { get; set; }
}

它是我的数据传输对象 (DTO) 以避免匿名类型错误

  public class LikesandPictureDetails
{
    public int IdPicturess { get; set; }
    public int IdUserPic { get; set; }
    public string PicTitle { get; set; }
    public string picFilename { get; set; }
    public System.DateTime? PicTime { get; set; }
    public int Likes { get; set; }
    public int NudityLevel { get; set; }
    public int FakesLevel { get; set; }
    public int IdPicturelike { get; set; }
    public int IdUser { get; set; }
    public System.DateTime? IdDatetime { get; set; }
    public int IduserLikedby { get; set; }
    public int LikeNumber { get; set; }
    public int IdPictures { get; set; }
    public float totalrating { get; set; }
    public int Count { get; set; }
}

我成功地计算了图片的个人评分,然后除以他们的计数。现在我想在我的图片详细信息表中显示总评分。如何实现这个东西?这是我的代码:

var query =
            db.picturelikes.GroupBy(n => n.idpictures).Select(group =>
                     new LikesandPictureDetails
                     {
                         IdPictures = group.Key,
                         totalrating = (group.AsEnumerable().Sum(o => o.individualrating)) / group.Count(),

                     });

这里 likesandpicturedetails 充当 dto。

4

1 回答 1

1

好吧,首先你应该使用方法Average来计算平均值。但是在您的情况下但是,由于您需要计算总体评分,为什么不在同一步骤中计算总和和平均值:

 db.picturelikes.GroupBy(n => n.idpictures).Select(group =>
 new LikesandPictureDetails
 {
     IdPictures = group.Key,
     averageRating = (group.AsEnumerable().Average(o => o.individualrating)),
     totalRating = (group.AsEnumerable().Sum(o => o.individualrating)),     
 });
于 2013-09-25T11:13:07.043 回答