使用 Linq 搜索不区分大小写的 IList 对象

本文关键字:IList 对象 大小写 Linq 搜索 不区 使用 | 更新日期: 2023-09-27 18:32:58

专家。我想在我的 IList 中搜索"名称"字段...但它始终区分大小写。如何在不区分大小写的情况下进行搜索?以下是我的代码:

型:

public IList<Student> Search(IList<Student> list, string keyword)
{
    return list.Where(e => e.Name.Contains(keyword)).ToList();
}

类:

public class Student
{
    public string Name {get;set;}
    public string MatricNo {get;set;}
    public string Gender {get;set;}
}

控制器:

IList<Student> list = new List<Student>();
Student students1 = new Student();
students1.Name = "Mike";
students1.MatricNo = "12345";
students1.Gender = "Male";
list.Add(students1);
Student students2 = new Student();
students2.Name = "Steve";
students2.MatricNo = "12345";
students2.Gender = "Male";
list.Add(students2);
Student students3 = new Student();
students3.Name = "Jane";
students3.MatricNo = "12345";
students3.Gender = "Male";
list.Add(students3);
string keyword = "mik"; //Example of search keyword
list = _searchModel.Search(list, keyword);

我想要名叫迈克的返回学生列表,但它没有返回。相反,仅当关键字 = "Mik" 时,它才会返回。当关键字="mik"时,如何在不区分大小写的情况下进行搜索?请注意,关键字可以是学生"姓名"的子字符串。

使用 Linq 搜索不区分大小写的 IList 对象

我使用 .ToLower() 它在 LinqPad 中对我来说工作得很好。 我更改了搜索关键字以使用更多变体,只是为了更清楚地显示结果。

我的代码正是:

void Main()
{
    IList<Student> list = new List<Student>();
    Student students1 = new Student();
    students1.Name = "Mike";
    students1.MatricNo = "12345";
    students1.Gender = "Male";
    list.Add(students1);
    Student students2 = new Student();
    students2.Name = "Steve";
    students2.MatricNo = "12345";
    students2.Gender = "Male";
    list.Add(students2);
    Student students3 = new Student();
    students3.Name = "Jane";
    students3.MatricNo = "12345";
    students3.Gender = "Male";
    list.Add(students3);
    var test1 = Search(list, "mik"); //returns Mike
    var test2 = Search(list, "MIK"); //returns Mike
    var test3 = Search(list, "iKe"); //returns Mike
    //all three are the same
}
public IList<Student> Search(IList<Student> list, string keyword)
{
    return list.Where(e => e.Name.ToLower().Contains(keyword.ToLower())).ToList();
}
public class Student
{
    public string Name {get;set;}
    public string MatricNo {get;set;}
    public string Gender {get;set;}
}