LINQ query with a WHERE clause with multiple conditions

前端 未结 2 1641
面向向阳花
面向向阳花 2021-02-09 10:11

I use EntityFramework with POCOs.
Suppose I have POCOs defined like this (simplified):

class Class1
{
    public int ID;
    public int SomeNumber;
}

class          


        
相关标签:
2条回答
  • 2021-02-09 10:48

    According to your logic, if x.Class1 is not null, but x.Class1.SomeNumber is 3, it won't check all the other clauses.

    If you want to check, if just some ClassN.SomeNumber == SomeNumber, then you should do it like this:

    int SomeNumber = 1; // some number 
    List<SomeClass> retValue = result 
        .Where(x => 
            { 
                if (x.Class1 != null && x.Class1.SomeNumber == SomeNumber) 
                    return true;
                else if (x.Class2 != null && x.Class2.SomeNumber == SomeNumber) 
                    return true;
                else if (x.Class3 != null && x.Class3.SomeNumber == SomeNumber) 
                    return true;
                return false;
            }) 
        .ToList();
    
    0 讨论(0)
  • 2021-02-09 10:50

    IMHO you should be OK with just this:

    Database DB = new Database(); 
    var result = DB.SomeClass.Where(x =>
                                Number == x.Class1.SomeNumber ||
                                Number == x.Class2.SomeNumber ||
                                Number == x.Class3.SomeNumber)
                             .ToList();
    

    Your query loads all data and after that you evaluate condition in .NET = you must test null value prior to accessing SomeNumber but that is not needed if you evaluate SomeNumber in SQL through Linq-to-entities. Linq-to-entities should perform automatic null coalescing.

    0 讨论(0)
提交回复
热议问题