多条件动态LINQ 组合查询

Posted 许鸿飞

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了多条件动态LINQ 组合查询相关的知识,希望对你有一定的参考价值。

本文章转载:http://www.cnblogs.com/wangiqngpei557/archive/2013/02/05/2893096.html

参考:http://dotnet.9sssd.com/entfwk/art/960

 http://www.cnblogs.com/killuakun/archive/2008/08/03/1259389.html

http://www.cnblogs.com/snowdream/archive/2008/07/18/1246308.html

 

以往我们都是通过判断的方式来拼接查询的SQL字符串,但是现在我们面对是强类型的LINQ查询,是否可以很方便的进行类似查询。

 

eg:

string _UserID = string.Empty;
           _UserID = "E351D301-F64B-412C-B9EF-573F41235AF2";
 
           string _UserName = string.Empty;
           _UserName = "admin";
 
           string _employyName = string.Empty;
           _employyName = "测试1";
 
           using (var xj = new XJGasBottles_testDataContext())
           {
               //Linq写法
               var usersLinq = from us in xj.Users
                               where (string.IsNullOrEmpty(_UserID) || us.UserID.ToString() == _UserID)
                                      && (string.IsNullOrEmpty(_UserName) || us.UserName == _UserName)
                                      || (us.EmpName == _employyName)
                               //where string.IsNullOrEmpty(_UserID) || us.UserID.ToString()==_UserID
                               //where string.IsNullOrEmpty(_UserName) || us.UserName==_UserName
                               select us;
               foreach (var item in usersLinq)
               {
                   Console.WriteLine("Linq:");
                   Console.WriteLine(item.UserID + "_" + item.UserName);
 
               }
 
               //Lamda写法
               var usersLamda = xj.Users.Where(s => (string.IsNullOrEmpty(_UserID) || s.UserID.ToString() == _UserID) &&
                                               (string.IsNullOrEmpty(_UserName) || s.UserName == _UserName) ||
                                               (s.EmpName==_employyName)
                                         )
                                   .Select(s => s);
 
               foreach (var item in usersLamda)
               {
                   Console.WriteLine("Lamda:");
                   Console.WriteLine(item.UserID + "_" + item.UserName);
 
               }
 
           }

 

以上是关于多条件动态LINQ 组合查询的主要内容,如果未能解决你的问题,请参考以下文章

Linq to Entity 多条件 OR查询

Linq动态条件

在 linq 查询中按条件过滤

ibatis动态多条件组合查询以及模糊查询

Mybatis -- 动态Sql概述动态Sql之<if>(包含<where>)动态Sql之<foreach>sql片段抽取

C#-WebForm-★★★LinQ-数据的条件组合查询并进行分页展示(未加各种限定)★★★