你好,我正在制作一个 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/