Using Linq to Join,Group By and Count… facing a tr

2019-09-20 06:57发布

I have two tables, picture and pictureratings in my db.

public partial class picture
{
    public int idpicture { 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 nuditylevel { get; set; }
    public int fakeslevel { get; set; }

    // This property will hold the total accumulated/summed 
    // up rating of a picture
    public int totalrating { get; set; }    
}

public partial class pictureratings 
{
    public int idrating { get; set; }
    public int idpictures { get; set; }
    public int iduser { get; set; }
    public System.DateTime iddatetime { get; set; }
    public int iduserrateddby { get; set; }
    public int rating { get; set; } 
}

For every rating a new pictureratings row will be created. I want to group pictureratings table by the picture id and then count the likes. I want to show those likes in picture table in totalrating property.

So as per my research till now, I am able to write this code

var total = from p in db.picturedetails
            join l in db.picturelikes on p.idpictures equals l.idpictures 
            group l by l.idpictures into g
            select new 
            {
                IdUserPic = g.First().iduser,
                IdPictures = g.First().idpictures,
                totalrating = g.Count()    
            }

I am using web api to return query total. So here comes my problem: how to show the picture properties like iduser, picTitle, picFilename, pictime, nuditylevel and fakeslevel? Am I doing it right? How should I do it?

2条回答
我只想做你的唯一
2楼-- · 2019-09-20 07:12

I think a group join is what you're looking for:

var total = from p in db.picturedetails
            join l in db.picturelikes on p.idpicture equals l.idpictures into pl
            select new
            {
                Picture = p,
                AverageRating = pl.Any()
                                    ? pl.Average(l => l.rating)
                                    : (double?)null,
                RatingsCount = pl.Count(),
                TotalRating = pl.Sum(l => (float?)l.likenumber) ?? 0
            };

If a picture has no likes, this will give a 0 total and null average for that picture.

查看更多
爱情/是我丢掉的垃圾
3楼-- · 2019-09-20 07:27

You could group an anonymous class. That way you can access both p & l properties.
Looks like this :

var total = from p in db.picturedetails
            join l in db.picturelikes on p.idpictures equals l.idpictures 
            group new {p,l} by l.idpictures into g
            select new 
            {
                IdUserPic = g.First().p.iduser,
                IdPictures = g.First().p.nuditylevel,
                totalrating = g.Count()    
            }
查看更多
登录 后发表回答