专家。我想搜索名称'我的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);
我希望列表中的返回学生名为Mike,但它不会返回。相反,它只会在关键字=&#34; Mik&#34;时返回。关键字=&#34; mik&#34 ;?如何在不区分大小写的情况下进行搜索请注意,关键字可以是&#39;名称&#39;的子字符串。学生。
答案 0 :(得分:2)
我使用.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;}
}