【问题标题】:How to join when using groupby使用groupby时如何加入
【发布时间】:2013-09-25 11:03:53
【问题描述】:

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

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。

【问题讨论】:

  • 问题是什么?如何将您的查询结果加入...?
  • 问题是如何修改picturedetails表中的总评分。

标签: sql linq lambda


【解决方案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)),     
 });

【讨论】:

  • 那你有什么问题?你不能用你的图片标记应用已经计算的值吗?在这些预先计算的组中,您确实有图片的 ID。只需使用Where linq 子句拍摄一张与您的照片相对应的照片。
  • 问题是如何在我的图片详细信息表中添加这些值。
  • 您的意思是在某种 POCO 类中建模还是要更新数据库?请编辑您的 OP,提供需要更改的内容以及它的结构。
  • @Hmmmmmmmmmm,你确定吗?似乎没有进行任何更改。
  • 现在改了,上次没保存。
猜你喜欢
  • 1970-01-01
  • 2015-11-23
  • 1970-01-01
  • 1970-01-01
  • 2017-04-25
  • 2021-02-15
  • 1970-01-01
  • 2022-01-12
  • 1970-01-01
相关资源
最近更新 更多