Linq实现字符串拼接多条件查询

时间:2019-09-18
本文章向大家介绍Linq实现字符串拼接多条件查询,主要包括Linq实现字符串拼接多条件查询使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

Linq实现字符串拼接多条件查询

 开发过程中,为提升用户体验,经常会使用到多条件查询,本篇博客介绍如何使用Linq实现字符串拼接多条件查询

 一般SQL字符串拼接

 1  string sql = "select * from StuInfo s inner join Class c on s.CId=c.CId where 1=1";
 2  if (sid != 0)
 3  {
 4      sql += " and s.SId=" + sid;
 5  }
 6  else if (sname != null)
 7  {
 8      sql += " and s.SName='" + sname + "'";
 9  }
10  return sql.ToString();

Linq字符串拼接

 1  var stu = from s in _context.StuInfo
 2            join c in _context.Class on s.CId equals c.CId
 3            select new
 4            {
 5                s.SId,
 6                s.SName,
 7                s.SSex,
 8                s.SAge,
 9                s.SHobby,
10                c.CName
11            };
12  if (sid != 0)
13  {
14      stu = stu.Where(p => p.SId == sid);//使用lambda表达式
15  }
16  else if (sname != null)
17  {
18      stu = stu.Where(p => p.SName.Contains(sname));
19  }
20  stu.ToList();//所有的if只有到此处才会执行

 End!

原文地址:https://www.cnblogs.com/gygg/p/11539541.html