按复杂数据库集分组

时间:2014-12-11 13:28:51

标签: c# linq

我的User对象会带来他回答的用户数据问题

我需要向用户显示并计算他回答最多的问题类型。假设他回答了3个类型A,1个类型B和4个类型C的有效问题。然后我需要显示他的数据,4和C.

这是我的Result班级

public class Result
{
    public int ResultID { get; set; }
    public int userID { get; set; }
    public int questionID { get; set; }
    public string type { get; set; }
    public int valid { get; set; }

    public virtual User User { get; set; }
    public virtual Question Question { get; set; }
}

这是我的User班级

public class User
{
    public int userID { get; set; }
    public string name { get; set; }

    public virtual ICollection<Result> Results { get; set; }
}

1 个答案:

答案 0 :(得分:1)

假设valid必须是正数:

var participantsWithBestResults = db.Participantes.Where(x => x.Results.Any(y => y.valid > 0))
.Select(x => new
{
    user = x,
    bestResult = x.Results.Where(y => y.valid > 0)
        .GroupBy(y => y.type)
        .OrderByDescending(y => y.Count())
        .Select(y => new
        {
            type = y.Key,
            count = y.Count()
        })
        .FirstOrDefault()
});