linq 实现查询字符串拼接 : And 和 OR 两种方式

从SQL到LINQ的查询转变
本文通过对比传统SQL字符串拼接的方式与使用LINQ进行条件查询的方法,展示了LINQ在.NET平台上的强大功能。文章详细介绍了如何利用LINQ优雅地实现动态查询,并提供了具体的代码示例。
  1. N年前我们是这样来 拼接查询字符串的:

     

     

     

    [c-sharp]  view plain  copy
     
    1. public string Test(string a, string b, string c,string d)  
    2.    {  
    3.        string sql = "SELECT * FROM Users WHERE 1=1";  
    4.        if (!string.IsNullOrEmpty(a))  
    5.        {  
    6.            sql += " AND name='" + a + "'";  
    7.        }  
    8.        if (!string.IsNullOrEmpty(b))  
    9.        {  
    10.            sql += " AND age='" + b+ "'";  
    11.        }  
    12.        if (!string.IsNullOrEmpty(c))  
    13.        {  
    14.            sql += " AND sex='" + c + "'";  
    15.        }  
    16.        if (!string.IsNullOrEmpty(d))  
    17.        {  
    18.            sql += " AND address='" + d + "'";  
    19.        }  
    20.        return sql.ToString();  
    21.    }  
     

     

     

    现在我们使用linq来实现上边的代码:

     

     

    [c-sharp]  view plain  copy
     
    1. public void Test(string a, string b, string c,string d)  
    2.        {  
    3.            QueryContext query = new QueryContext();  
    4.            var q = from u in query.Users  
    5.                     select u;  
    6.            if (!string.IsNullOrEmpty(a))  
    7.            {  
    8.                q = q.Where(p => p.name == a);  
    9.            }  
    10.            if (!string.IsNullOrEmpty(b))  
    11.            {  
    12.                q = q.Where(p => p.age == b);  
    13.            }  
    14.            if (!string.IsNullOrEmpty(c))  
    15.            {  
    16.                q = q.Where(p => p.sex == c);  
    17.            }  
    18.            if (!string.IsNullOrEmpty(d))  
    19.            {  
    20.                q = q.Where(p => p.address == d);  
    21.            }  
    22.            q.ToList();  //上边的所有if,只有到此处才会执行  
    23.        }  

     

转载于:https://www.cnblogs.com/tsql/p/8570893.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值