欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

c#中如何使用到模糊查询

程序员文章站 2022-05-03 11:41:33
c#中如何使用到模糊查询,先举个最简单实用的例子,可在vs控制台应用程序中输出: 定义实体类: public class Student { public int ID { get; set; } public string Name { get; set; } public int? Age { ......

c#中如何使用到模糊查询,先举个最简单实用的例子,可在vs控制台应用程序中输出:

定义实体类:

 public class student
        {
            public int id { get; set; }
            public string name { get; set; }
            public int? age { get; set; }
            public string sex { get; set; }
        }
 
为实体类赋值存放到集合list中:
 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 = "女";
  方法一:linq
   list<student> resultlist = (from c in lsstudent where  c.name.contains(key) ||c.sex.contains(sex) select c).tolist();
  知识讲解
  1,contains("key"),---意义等同于ql server中的like '%key%',从两端模糊匹配
  2,startswith("key"),---意义等同于sql server中的like 'key%',从开头模糊匹配
  3,endswith("key"),---意义等同于sql server中的like '%key',从结尾模糊匹配
 
 方法二
   list<student> resultlist = lsstudent.where(str => str.name.contains(key) || str.sex.contains(key)).tolist();
 
  方法三
   list<student> resultlist = (from c in lsstudent where c.name.indexof(key)>=0 ||c.sex.indexof(sex)>=0 select c).tolist();
  知识讲解
  1,c.name.indexof(key)>=0 ---意义等同于 like '%key%',从两端模糊匹配
  2,c.name.startswith(key) ---等同于like 'key%' ,从开头模糊匹配
  3,c.name.endwith(key) ---等同于like '%key',从结尾模糊匹配
  vs控制台输出打印代码:
 
  string json = jsonconvert.serializeobject(resultlist, newtonsoft.json.formatting.indented);
  console.writeline(json);