“Where”子句中的动态表达式 – Linq to SQL

我是LINQ的新手,所以我希望这不是一个愚蠢的问题:

我在数据网格中有一个包含大量内容的表格,我希望用户能够通过使用网格上方的一些combobox来过滤网格[如搜索栏]

我创建了一个方法,它接受combobox中的文本,并将其放在“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; } 

现在我遇到了一个问题:我希望用户能够将其中一个combobox留空,如果他这样做,这意味着他不想过滤该标准。 [EG – 组合“RMcmbDis”具有“Math”且状态组合[“RMcmbStatus”]为空,因此网格将仅在所有状态中显示“Math”。

我怎么做? 谢谢你们… N.

如果你想要的条件是真的,你可以添加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; 

请参阅下面的评论,了解处理大量filter的一个选项。 另一种选择是使用辅助方法:

 T AddFilter(IQueryable results, string filterValue, Expression> 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; 

您可以根据您拥有的条件添加多个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); }