c#中如何使用到模糊查询,先举个最简单实用的例子,可在vs控制台应用程序中输出:
定义实体类:
public class Student
{
public int ID { get; set; }
{
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 = "女" }
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 = "女";
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 = 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();
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);
Console.WriteLine(json);