本文章轉載: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);
}
}
