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);