【发布时间】:2014-09-11 19:38:37
【问题描述】:
我有一个模型类 Person 有字段:public string LastName { get; set; } 。我想在我的db 中浏览表Persons 中所有姓氏首字母为A 或Ą 的人,并按姓名对他们进行分组。
我的查询有问题。我不知道如何选择所有这些人,或者我不知道如何从第 51 人到第 100 人中选择
我试过了:
public ActionResult Index() {
var list = from person in db.Persons where (person.LastName.StartsWith('A'+"") ||person.LastName.StartsWith('Ą'+"") ) HOW TO SELECT AND GROUP THEM HERE
return View(list);//argument should be of type List<Person>
}
问题:如何获取所有名字以'A'或'Ą'开头的人或表中第51到第100位的人?
编辑:
回答有帮助,但我无法将其转换为 List
public ActionResult Index(/*char lastNameFirstLetter = 'A'*/) {
var queryResult = db.Persons.Where(person => person.LastName.StartsWith("A"))
.OrderBy(person => person.Id) // you need OrderBy before Skip
.GroupBy(person => person.LastName);
var list = queryResult.ToList();
return View(list);
}
当我转到 Index.cshtml 视图时,我得到黄屏死机:
The model item passed into the dictionary is of type 'System.Collections.Generic.List`1[System.Linq.IGrouping`2[System.String,WebApplication2.Models.Person]]', but this dictionary requires a model item of type 'System.Collections.Generic.IEnumerable`1[WebApplication2.Models.Person]'.
Index的型号是:
@model IEnumerable<WebApplication2.Models.Person>
【问题讨论】:
-
您可能需要
OrderBy、Skip和Take。它们用于分页 -
将
@model IEnumerable<WebApplication2.Models.Person>更改为@model List<WebApplication2.Models.Person>
标签: c# sql asp.net-mvc linq