c#中如何使用到模糊查询
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);
我爱代码,代码使我快乐!
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· 从HTTP原因短语缺失研究HTTP/2和HTTP/3的设计差异
· 三行代码完成国际化适配,妙~啊~