LINQ with Entity Framework中的嵌套组

时间:2016-02-26 09:39:27

标签: c# linq entity-framework-6

我在下面有一个查询,它按照classgroupenrollment对学生的结果数据进行分组,如代码所示

public List<PassingRatioDTO> GetStudentPassingRatio()
{
    using(SMSEntities em=new SMSEntities())
    {
        try
        {
            List<PassingRatioDTO> result = (from results in em.ResultDetails
                    where results.ExamDate.Year == 2016
                    group results by new {results.Class_Id, results.Group_Id, results.EnrollmentId } into groupedRresult
                    select new PassingRatioDTO()
                    {
                        Percentage = (((groupedRresult.Where(s => s.Status == "Pass").Count()) * 100) / groupedRresult.Count()),
                        ClassName = groupedRresult.Where(s => s.Class_Id == s.ClassDetail.Class_Id).Max(s => s.ClassDetail.ClassName),
                        GroupName = groupedRresult.Where(s => s.Group_Id == s.GroupDetail.Group_Id).Max(s => s.GroupDetail.Group_Name),
                        Year = groupedRresult.Max(s => s.ExamDate.Year),
                    }
            ).ToList();

            return result;
        }
        catch(Exception ex)
        {
            return null;
        }
   }

我想再次对此查询结果进行分组并计算百分比(这是一个派生列),其中百分比大于40 ..

1 个答案:

答案 0 :(得分:0)

如果您有初始查询结果,则可以按分组条件(ClassName)对其进行分组,并计算符合条件(Count(x => x.Percentage > 40))的组内条目数:

var results = GetStudentPassingRatio();
var passingCounts = from result in results
    group result by result.ClassName into classResults
    select new /* some object type */
    {
        ClassName = classResults.Key,
        PassCount = classResults.Count(x => x.Percentage > 40)
    };