linqtoEF分组查询groupby的使⽤
第⼀种:查询表达式语法:
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分组.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);
}
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论