第一种:查询表达式语法:
IQueryable<EnrollmentDateGroup> data = from student in db.Students group student by student.EnrollmentDate into dateGroup select new EnrollmentDateGroup() { EnrollmentDate = dateGroup.Key, StudentCount = dateGroup.Count() }; return View(data.ToList());第二种:方法labmda语法:
var context = new SiteDataContext(); var notifications = context.Notifications .Where(n => n.UserId == userId) .Where(n => !n.IsDismissed) .GroupBy(n => n.NotificationType) .Select(g => new NotificationViewModel { Count = g.Count(), NotificationType = g.Key.ToString(), BadgeClass = NotificationType.Email == g.Key ? "success" : "info" }); 实际使用过的例子:使用的是方法+labmda
[ChildActionOnly]
public ActionResult IndexCourseOnClickRange()
{
var courseList =new List<IndexClickRangeOnCourseViewModel>(); //先建立一个list .
var _coursesByClick = _resourceService.FindAll().Where(r => r.ResourceIsShow == true) //也可以使用ContextFactory.GetCurrentContext().Source取得课程资源。
.GroupBy(r => r.CourseID)
.Select(g => new IndexClickRangeOnCourseViewModel
{
CourseID = g.Key,
CourseResourceCount =g.Count(),
CourseResourceTotalClickCount = g.Sum(x =>x.ClickCount) //对分组后的数据 按点点击量汇总。
});
var _courses = _coursesByClick.ToList(); //这里是重点,必须使用tolist方法来立即执行,从数据库中获取值,如果不立即执行,延迟执行将会发生错误。
foreach (var item in _courses)
{
Course course =_courseService.Find(item.CourseID);;
courseList.Add(new IndexClickRangeOnCourseViewModel { CourseID = item.CourseID, CourseName = course.CourseName, CourseType=course.CourseType, CourseResourceCount=item.CourseResourceCount , CourseDescription =course.CourseDescription, PriorOrder = course.PriorOrder, CourseResourceTotalClickCount = item.CourseResourceTotalClickCount });
}
// var courses = _coursesByClick.ToList() as IEnumerable<Course>;
// var courses = _coursesByClick.OrderByDescending(c => c.CourseResourceTotalClickCount) as IQueryable<IndexClickRangeOnCourseViewModel>;
var coursesOrder =courseList.OrderByDescending(c => c.CourseResourceTotalClickCount).ThenBy(c => c.PriorOrder) as IEnumerable<IndexClickRangeOnCourseViewModel>; //排序后变成了IOrder ,为了使用take取前面的序列,必须转换成IEnumerable ;
if(coursesOrder.Count() >=7)
{
coursesOrder =coursesOrder.Take(7);
}
return PartialView("_IndexCourseOnClickRange", coursesOrder);
}