首页 .NET/Web 如何用C#的 Linq进行模糊查询

如何用C#的 Linq进行模糊查询

作者:胡同里的砖头 围观群众:402 更新于:2023-09-27

List<Student> lsStudent = new List<Student>(){
new Student { ID = 1,Name = "1", Age = 128, Sex = null },
new Student { ID = 2, Name = "2", Age = 18, Sex = "女" },
new Student { ID = 3, Name = "31", Age = 13, Sex = "男" },
new Student { ID = 4, Name = "4", Age = 23, Sex = "男" },
new Student { ID = 5, Name = "51", Age = null, Sex = "女" },
new Student { ID = 6, Name = "6", Age = null, Sex = "女" },
new Student { ID = 7, Name = "7", Age = null, Sex = "女" }
};
模糊查询条件:根据Name=1或者Sex=女模糊查询
string key = “1”;
string sex = “女”;
方法一
List<Student> resultList = (from c in lsStudent where c.Name.Contains(key) ||c.Sex.Contains(sex) select c).ToList();

方法二
List<Student> resultList = lsStudent.Where(str => str.Name.Contains(key) || str.Sex.Contains(key)).ToList();

知识讲解:
Contains(“key”),—意义等同于ql server中的like ‘%key%’,从两端模糊匹配
StartsWith(“key”),—意义等同于sql server中的like ‘key%’,从开头模糊匹配
EndsWith(“key”),—意义等同于sql server中的like ‘%key’,从结尾模糊匹配

方法三
List<Student> resultList = (from c in lsStudent where c.Name.IndexOf(key)>=0 ||c.Sex.IndexOf(sex)>=0 select c).ToList();

知识讲解:
c.Name.IndexOf(key)>=0 —意义等同于 like ‘%key%’,从两端模糊匹配
c.Name.StartsWith(key) —等同于like ‘key%’ ,从开头模糊匹配
c.Name.EndWith(key) —等同于like ‘%key’,从结尾模糊匹配

  • 本文标题: 如何用C#的 Linq进行模糊查询
  • 文章分类:【.NET/Web】
  • 非特殊说明,本文版权归【胡同里的砖头】个人博客 所有,转载请注明出处.
留言评论
站点声明:
1、本站【胡同里的砖头】个人博客,借鉴网上一些博客模板,取其各优点模块自行拼装开发,本博客开发纯属个人爱好。
2、所有笔记提供给广大用户交流使用,可转载,可复制,纯个人开发所遇问题锦集记录使用
Copyright © huzlblog.com All Rights Reserved. 备案号:苏ICP备2021056683号-8