使用groupby时如何加入

时间:2013-09-25 11:03:53

标签: sql linq lambda

我在mydatabase中有两张picturedetails和picture like表。

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(),

                     });

这里likeandpicturedetails正在充当dto。

1 个答案:

答案 0 :(得分: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)),     
 });