LINQ中的条件Where子句 [英] Conditional Where clause in LINQ

查看:56
本文介绍了LINQ中的条件Where子句的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我在网格中显示数据,并且我有许多文本框用于过滤数据. 员工编号的文本框.如果员工ID文本框为空,则不添加任何where子句,但如果不为空,则为此添加where子句.如果薪水文本框具有值或雇员姓名文本框具有值,我们可以使用相同的方法来过滤数据.

suppose i am showing data in grid and i have many textboxes for filter the data. textbox for employee id. if employee id textbox is empty then no where clause will be added but if it is not empty then where clause will be added for that. the same way we can filter data if salary textbox has value or employee name textbox has value.

我尝试编写条件LINQ查询,但出现错误.这是我的

i try to compose a conditional LINQ query but got error. here is mine

var sName="";

var r = from t in TblFamilies
where 1 == 1
if(sName!="")
{
  && t.Name="Keith";
};

select new
{
    t.ID,
    t.ParentID,
    t.Name,
    t.CurDate
};

r.Dump();               

推荐答案

尝试一下:-

首先选择数据:-

var r = from t in TblFamilie
select new
{
    t.ID,
    t.ParentID,
    t.Name,
    t.CurDate
};

然后您可以根据条件进行过滤:-

Then you can filter based on condition:-

   if (sName!="")
        r = r.Where(x => x.Name == sName);

这篇关于LINQ中的条件Where子句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆