c# - 如何使用 bool 条件使用 C# LINQ 从列表中获取对象?

标签 c# asp.net-mvc linq

你好,我正在制作一个 Controller ,通过它的 URL,你可以从列表中获取某些项目。如果您输入一个字母,则硬编码列表中姓氏以字母开头的所有学生都会显示在网页上。但我在 LINQ 查询上遇到了困难,因为当使用下面的代码时,无论如何我都会得到一个空白页面。我做错了什么以及如何获取我需要的元素并将它们放入列表中?

编辑:URL 中的小写是问题所在。谢谢!

public IActionResult Surname(string letter)
{
    string query = letter;
    //  if(letter != null) { query = letter; }
    List<Student> studenten = new List<Student>()
    {
        new Student { Naam = "Johan", Achternaam = "Jacobs" },
        new Student { Naam = "Karel", Achternaam = "Jay" },
        new Student { Naam = "John", Achternaam = "Jas" }
    };

    List<Student> newStudents = studenten.Where(x => x.Achternaam.StartsWith(query) == true)
                                         .ToList();

    ViewData["Student"] = newStudents;

    return View();
}

最佳答案

您应该使用 StartsWith 方法的重载:

public bool StartsWith(
    string value,
    bool ignoreCase,  // set this as true
    CultureInfo culture // set this as invariant culture
)

var newStudents = studenten.Where(x => x.Achternaam
                                         .StartsWith(
                                               query, 
                                               true,
                                               CultureInfo.InvariantCulture))
                           .ToList();

如果您的网址如下:

Controller/Index/?letter=j 

或者这个:

Controller/Index/?letter=J

您总是会得到您正在寻找的结果。

关于c# - 如何使用 bool 条件使用 C# LINQ 从列表中获取对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47396076/

相关文章:

html - 如何在 MVC 5 中实现 Bootstrap Sidebar

JSON.NET 使用 linq 选择数组中的项目

linq - Moq First()Last()和GetEnumerator()怪异

c# - 使用 GPU 加速 BigInteger 计算

asp.net-mvc - Azure 和 TFS,如何与加入团队的新开发人员共享我的项目

c# - 使用无符号原始类型

javascript - ASP.NET MVC 下拉列表更改以在没有 Javascript 的情况下导致回发

c# - 将条件为 "In"的 SQL 查询转换为 Lambda 表达式

c# - CRM 2013 - 在 View 中排序记录

c# - 文本框的 wpf LostFocus 事件