【问题标题】:Linq query to people whose last name starts with letter 'A'Linq 查询姓氏以字母“A”开头的人
【发布时间】: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>

【问题讨论】:

  • 您可能需要OrderBySkipTake。它们用于分页
  • @model IEnumerable&lt;WebApplication2.Models.Person&gt;更改为@model List&lt;WebApplication2.Models.Person&gt;

标签: c# sql asp.net-mvc linq


【解决方案1】:

我想你想要这样的东西:

db.Persons.Where(person => person.LastName.StartsWith("A"))
  .OrderBy(person => person.Id) // you need OrderBy before Skip
  .Skip(50)
  .Take(50)
  .GroupBy(person => person.Name);

【讨论】:

  • 不,不,请不要使用 lambda 表达式。我只是要求 linq 查询。
  • 这是一个 linq 查询
  • @Yoda,没有 lambdas 你怎么做 linq?我的意思是,您可以创建自己的函数并调用它们,但这更费力。
  • 我在OP中发布的查询风格怎么称呼?下次我现在将如何更好地询问。
  • @Yoda 你需要删除 GroupBy 然后
猜你喜欢
  • 1970-01-01
  • 2013-11-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-05-19
  • 2022-08-14
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多