【问题标题】:Search IList object without case sensitive using Linq使用 Linq 搜索不区分大小写的 IList 对象
【发布时间】:2016-05-10 17:32:57
【问题描述】:

专家。我想在我的 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 的学生的列表,但它没有返回。相反,它只会在关键字 = "Mik" 时返回。当关键字=“mik”时如何进行不区分大小写的搜索?请注意,关键字可以是学生“姓名”的子字符串。

【问题讨论】:

  • 我也试过 list.Where(e => e.Name.ToLower().Contains(keyword.ToLower())) 但仍然区分大小写...
  • 你可以看看这个问题stackoverflow.com/questions/18378448/…
  • 抱歉,Kote,我对我的问题进行了一些更改...关键字可以是子字符串...这样有效吗?
  • @erntay2 您确定您的 ToLower 比较(两者上)不起作用吗?
  • @erntay2 抱歉,链接错误。看这个:stackoverflow.com/questions/444798/…

标签: c# linq list asp.net-mvc-4 search


【解决方案1】:

我使用 .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;}
}

【讨论】:

  • 是否返回所有 3 个学生记录?
  • 这样,有帮助吗?我在想 .ToLower() 可能不是你的问题。你如何测试输出?此外,jdweng 提出了一个很好的观点,即您正在重新分配“列表”变量。
猜你喜欢
  • 2023-04-01
  • 1970-01-01
  • 1970-01-01
  • 2010-09-15
  • 1970-01-01
  • 2013-09-26
  • 2023-03-20
  • 1970-01-01
  • 2017-06-30
相关资源
最近更新 更多