在mvc项目中我正在使用这种方法。但是,当数据库变得越来越大时,它的速度非常慢。我该如何解决?
private List<SelectListItem> getDates() {
var db = new _Entities();
var list = new List<SelectListItem>();
var date = db.Location
.GroupBy(k => EntityFunctions.TruncateTime(k.DateServer))
.ToList();
//var date = db.Location.Select(m => m.DateService).Distinct();
foreach (var x in date)
{
list.Add(
new SelectListItem
{
Value = x.FirstOrDefault().DateServer.Date.ToShortDateString(),
Text = x.FirstOrDefault().DateServer.ToShortDateString()
} );
}
return list;
}
答案 0 :(得分:1)
您不应该创建列表和循环,而是使用数据库:
return db.Location.GroupBy(k => EntityFunctions.TruncateTime(k.DateServer))
.Select(group => new { group, first = group.First() })
.Select(x => new SelectListItem {
Value = x.first.DateServer.Date.ToShortDateString(),
Text = x.first.DateServer.ToShortDateString()
})
.ToList();
由于您按日期分组文本和值是相同的,因此可以简化:
return db.Location.GroupBy(k => EntityFunctions.TruncateTime(k.DateServer))
.Select(g => new SelectListItem { Value = g.Key.ToShortDateString(), Value = g.Key.ToShortDateString() })
.ToList();