优化数据检索

时间:2018-03-12 16:04:19

标签: c# linq

我正在尝试按如下方式检索每个班级的出勤率,但我想知道有更好的方法来处理它,而不是每个班级调用三次GetAttendanceLastMonth方法,有没有办法只调用一次获取所有这些信息。

List<Attendance> chemistry = GetAttendanceLastMonth(schoolId, chemistryId);
List<Attendance> math = GetAttendanceLastMonth(schoolId, mathId);
List<Attendance> music = GetAttendanceLastMonth(schoolId, musicId);
//Plotting them on the chart based on date (x axis) and attendance number(yaxis) values

public List<Attendance> GetAttendanceLastMonth(string schoolId, string classId)
{
   try
   {
       var attendanceNumber = Repository.Get(x => x.SchoolId.Equals(schoolId)).Where(x => x.ClassId.Equals(classId) && 
       (DateTime.Now.Date.Subtract(x.AttendanceDate.Date)).TotalDays >= 0 && 
       (int)(DateTime.Now.Date - x.AttendanceDate.Date).TotalDays <= 30).ToList();

       attendanceNumber.Sort((x, y) => x.AttendanceDate.CompareTo(y.AttendanceDate));
       return attendanceNumber ;
   }
   catch (Exception ex)
   {
   }
}

1 个答案:

答案 0 :(得分:1)

您可以返回字典,密钥为ClassId,值为List<Attendance>,您可以使用Contains检查多个ClassId

public Dictionary<string, List<Attendance>> GetAttendanceLastMonth(string schoolId, params string[] classIds)
{
    DateTime monthStart = DateTime.Today.AddDays(-DateTime.Today.Day);
    DateTime nextMonthStart = monthStart.AddMonths(1);

    Dictionary<string, List<Attendance>> attendancesDictionary = Repository
        .Get(x => x.SchoolId == schoolId)
        .Where(x => classIds.Contains(x.ClassId))
        .Where(x => x.AttendanceDate.Date >= monthStart && x.AttendanceDate.Date < nextMonthStart)
        .GroupBy(x => x.ClassId)
        .ToDictionary(g => g.Key, g => g.OrderBy(x => x.AttendanceDate).ToList());
    return attendancesDictionary;
}

您可以通过键访问每个列表:

Dictionary<string, List<Attendance>> attendancesDictionary =
   GetAttendanceLastMonth(schoolId, chemistryId, mathId, musicId);

// for example the music-list:
List<Attendance> music = attendancesDictionary[musicId];