Using Linq to join, group, and count.

I have two tables, pictureand pictureratingsin 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; } 
}

A new line will be created for each rating pictureratings. I want to group a table by pictureratingsimage identifier, and then count the ones I like. I want to show those who like the table picturein the property totalrating.

So, according to my research so far, I can 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 use web api to return the total. So here's my problem: how to display properties picture, such as iduser, picTitle, picFilename, pictime, nudityleveland fakeslevel? Am I doing it right? How should I do it?

0
2

. , p l.
:

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()    
            }
+1

, group join - , :

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
            };

, 0 total null .

+1

All Articles