2011-07-12 73 views
4

我是新的LINQ,所以我希望这不是一个愚蠢的问题:动态表达式中的“where”子句 - LINQ to SQL的

我有很多内容在DataGrid中提出了一个表,我希望用户能够通过在网格上方使用一些组合框来筛选网格[如搜索栏]

我创建了一个方法,它将组合框中的文本放在“Where”子句中:

public void find() 
    { 
     string disName; 
     string statusName; 


     disName = RMcmbDis.Text; //This Get the first string to filter 
     statusName = RMcmbStatus.Text; // this get the second string to filter 

//我在这里收集所有数据,我需要

 var allCNT = from x in cntDB.releases 
        join dis in cntDB.disciplines on x.discipline equals dis.discipline_id 
        join btch in cntDB.batches on x.batch_num equals btch.batch_id 
        join z in cntDB.status on x.status equals z.status_id 

        select new { dis.discipline_name, x.grade, x.batch_num, btch.batch_name, z.status_description, x.segment_leader, x.ped_leader, x.release_location, x.comments, x.QA_Verdict }; 

//我在这里做过滤

 var find = allCNT.Where(a => a.discipline_name == disName && a.status_description == statusName); 


     dataGridView1.DataSource = find; 
    } 

现在我有一个问题:我希望用户能够离开的组合框一个空的,如果他这样做,这意味着他不想过滤该标准。 [E.G - 组合“RMcmbDis”有“数学”,状态组合[“RMcmbStatus”]是空的,所以网格将只显示“所有状态下的数学”。

我该怎么做? 感谢球员... N.

回答

6

你可以只添加Where()条款,如果你想在条件为真...

var results = allCNT; 

if (!string.IsNullOrEmpty(disName)) 
    results = result.Where(a => a.discipline_name == disname); 

if (!string.IsNullOrEmpty(statusName)) 
    results = results.Where(a => a.status_description == statusName); 

dataGridView1.DataSource = results; 

见下文评论为处理大量的过滤器的一个选项。另一种选择是使用一个辅助方法:

T AddFilter<T>(IQueryable<T> results, string filterValue, Expression<Func<T, bool>> predicate) 
{ 
    if(!string.IsNullOrEmpty(filterValue)) 
     return results.Where(predicate); 
    return results; 
} 

,你会使用这样的:

var results = allCNT; 
results = AddFilter(results, disname, a => a.discipline_name == disname); 
results = AddFilter(results, statusName, a => a.status_description == statusName); 
results = AddFilter(results, whatever, a => a.whatever == whatever); 
// ... 
dataGridView1.DataSource = results; 
+0

非常感谢!但是如果有8个组合框?没有办法做类似的事情:a => a.status_descrition == * everything * && a.displince_name == * specific *? – Nim

+0

一种选择是构建一个如下所示的大型Where()子句:Where(a =>(disname ==“”|| a.discipline_name == disname)&&(statusName ==“”|| a.status_description == statusName)&& ...)' – dahlbyk

3

您可以添加多个Where条款取决于你有什么样的标准,如:

var find = allCNT; 
if (!string.IsNullOrEmpty(disName)) 
{ 
    find = find.Where(a => a.discipline_name == disName); 
} 
if (!string.IsNullOrEmpty(statusName)) 
{ 
    find = find.Where(a.status_description == statusName); 
} 
+0

非常感谢! – Nim