[英]LINQ query should be based on criteria
這對我來說可能有點棘手,因為我剛接觸LINQ。 我有以下LINQ代碼可以正確返回我的數據。 但是,給出的條件是選擇性的。 意思是,一次可能無法給出所有條件。條件是基於用戶輸入的。 因此,如何根據用戶選擇的標准編寫此類增量LINQ。
var dRows = (from TblPatientInformation in this.dsPrimaPlus1.tblPatientInformation
join TblDoctorMaster in this.dsPrimaPlus1.tblDoctorMaster on new { PtI_dcMId = Convert.ToInt32(TblPatientInformation.ptI_dcMId) } equals new { PtI_dcMId = TblDoctorMaster.dcM_Id }
join TblDepartmentMaster in this.dsPrimaPlus1.tblDepartmentMaster on new { DcM_deptMId = TblDoctorMaster.dcM_deptMId } equals new { DcM_deptMId = TblDepartmentMaster.ID }
join TblPatientDiagnosis in this.dsPrimaPlus1.tblPatientDiagnosis on new { PtI_Id = TblPatientInformation.ptI_Id } equals new { PtI_Id = Convert.ToInt32(TblPatientDiagnosis.ptD_ptIId) }
join TblDiagnosisInformation in this.dsPrimaPlus1.tblDiagnosisInformation on new { PtD_tgIId = Convert.ToInt32(TblPatientDiagnosis.ptD_tgIId) } equals new { PtD_tgIId = TblDiagnosisInformation.tgI_Id }
where
TblPatientInformation.ptI_Id > 0 ||
TblPatientInformation.ptI_PatientName.Contains(txtName.Text) ||
TblPatientInformation.ptI_Code == int.Parse( txtCaseNo.Text) ||
TblDepartmentMaster.ID ==int.Parse( cmbDepartment.SelectedValue.ToString()) ||
TblDoctorMaster.dcM_Id == int.Parse(cmbDoctor.SelectedValue.ToString()) ||
TblDiagnosisInformation.tgI_Id == int.Parse(cmbDiagnosis.SelectedValue.ToString())
select new
{
TblPatientInformation.ptI_Id,
TblPatientInformation.ptI_Code,
TblPatientInformation.ptI_PatientName,
TblPatientInformation.ptI_dcMId,
TblPatientInformation.ptI_Age,
TblPatientInformation.ptI_Address,
TblPatientInformation.ptI_eMail,
TblPatientInformation.ptI_Phone1,
TblPatientInformation.ptI_Phone2,
TblPatientInformation.ptI_Phone3,
TblPatientInformation.ptI_Date,
TblPatientInformation.ptI_Gender,
TblDiagnosisInformation.tgI_Name,
TblDiagnosisInformation.tgI_Description,
TblDoctorMaster.dcM_FullName,
TblDepartmentMaster.Department
});
我建議為此嘗試Predicate Builder http://www.albahari.com/nutshell/predicatebuilder.aspx 。
該帖子建議以下內容:
使用PredicateBuilder進行實驗的最簡單方法是使用LINQPad。 LINQPad允許您針對數據庫或本地集合立即測試LINQ查詢,並直接支持PredicateBuilder(按F4並選中“ Include PredicateBuilder”)。
這是采用這種方法的一種簡單方法。
希望能有所幫助。
一種解決方案是使用動態LINQ,您可以在其中指定字符串表達式而不是代碼表達式。 例如
// Dynamic Linq string expression
var result = context.People.Where("Age >= 3 And StreetNumber < 3").ToList();
相對於:
// Linq code expression
var result = context.People.Where(q=>q.Age>=3 && q.StreetNumber < 3).ToList();
這樣,您可以根據用戶輸入來解析表達式,例如
StringBuilder sb = new StringBuilder();
...
if(criteria1)
{
sb.Append(" And Criteria>1");
}
...
if(criteria2)
{
sb.Append(" And Criteria2<15");
}
...
var result = context.People.Where(sb.ToString()).ToList();
請查看此Scott Gu文章,以獲取完整示例:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.