LINQ Where with AND OR condition

后端 未结 3 1322
轮回少年
轮回少年 2021-02-12 01:22

So I have managed to get this query working

List listStatus = new List() ; 
listStatus.add(\"Text1\");

List listMercha         


        
相关标签:
3条回答
  • 2021-02-12 01:55

    Well, you're going to have to check for null somewhere. You could do something like this:

    from item in db.vw_Dropship_OrderItems
             where (listStatus == null || listStatus.Contains(item.StatusCode)) 
                && (listMerchants == null || listMerchants.Contains(item.MerchantId))
             select item;
    
    0 讨论(0)
  • 2021-02-12 02:14
    from item in db.vw_Dropship_OrderItems
        where (listStatus != null ? listStatus.Contains(item.StatusCode) : true) &&
        (listMerchants != null ? listMerchants.Contains(item.MerchantId) : true)
        select item;
    

    Might give strange behavior if both listMerchants and listStatus are both null.

    0 讨论(0)
  • 2021-02-12 02:15

    Linq With Or Condition by using Lambda expression you can do as below

    DataTable dtEmp = new DataTable();
    
    dtEmp.Columns.Add("EmpID", typeof(int));
    dtEmp.Columns.Add("EmpName", typeof(string));
    dtEmp.Columns.Add("Sal", typeof(decimal));
    dtEmp.Columns.Add("JoinDate", typeof(DateTime));
    dtEmp.Columns.Add("DeptNo", typeof(int));
    
    dtEmp.Rows.Add(1, "Rihan", 10000, new DateTime(2001, 2, 1), 10);
    dtEmp.Rows.Add(2, "Shafi", 20000, new DateTime(2000, 3, 1), 10);
    dtEmp.Rows.Add(3, "Ajaml", 25000, new DateTime(2010, 6, 1), 10);
    dtEmp.Rows.Add(4, "Rasool", 45000, new DateTime(2003, 8, 1), 20);
    dtEmp.Rows.Add(5, "Masthan", 22000, new DateTime(2001, 3, 1), 20);
    
    
    var res2 = dtEmp.AsEnumerable().Where(emp => emp.Field<int>("EmpID")
                == 1 || emp.Field<int>("EmpID") == 2);
    
    foreach (DataRow row in res2)
    {
        Label2.Text += "Emplyee ID: " + row[0] + "   &   Emplyee Name: " + row[1] + ",  ";
    }
    
    0 讨论(0)
提交回复
热议问题