gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 20:28:27 26 4
gpt4 key购买 nike

您好,我正在通过其 URL 制作一个 Controller ,您可以从列表中获取某些项目。如果您输入一个字母,则硬编码列表中姓氏以字母开头的所有学生都会显示在网页上。但是我正在为 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com