分组和排序

本文关键字:排序 | 更新日期: 2023-09-27 18:08:06

我有一个显示应用程序错误列表的页面。目前一切正常,并以最新日期先显示错误。我希望能够组的错误,它们来自应用程序,然后按日期排序。这是我目前所拥有的,但我不知道我需要添加什么才能按应用程序分组。有人能帮忙吗?

h2控制器

public ActionResult Index(string sortOrder, int? page)
{
    ViewBag.CurrentSort = sortOrder;
    ViewBag.DateSortParm = sortOrder == "TimeUtc" ? "timeutc_desc" : "TimeUtc";
    var applications = from s in db.ElmahErrors
                 select s;
    switch (sortOrder)
    {
        default:
            applications = applications.OrderByDescending(s => s.TimeUtc);
                break;
    }
    int pageSize = Int32.Parse(System.Configuration.ConfigurationManager.AppSettings["DefaultPageSize"]);
    int pageNumber = (page ?? 1);
    return View(applications.ToPagedList(pageNumber, pageSize));
}

分组和排序

有几种方法可以做到这一点,但最简单的方法是按应用程序排序,然后按日期排序:

applications = applications.OrderBy(x=>x.Application).ThenByDescending(s => s.TimeUtc);

您可以简单地使用GroupBy扩展方法:-

var applications = db.ElmahErrors.GroupBy(x => x.ApplicationName)
                                 .Select(x => new 
                                       {
                                          ApplicationName = x.Key,
                                          Errors = x.OrderByDescending(s => s.TimeUtc);
                                       });

这里,我认为应用程序名称存储在ApplicationName属性中。