AnotherDeveloper
AnotherDeveloper

Reputation: 1272

Linq Equivalent to Where Clause with Nested Conditions

The SQL Statement would like like this:

Select * From Table
Where 
Column1 = 'A' OR
(Column2 = 'A' AND
 Column3 = 'A')

So Column1 could be equal to 'A', or a combination of Column2 and Column3 equaling 'A' would constitute a match.

How could I write a linq statement to do the same thing?

Upvotes: 1

Views: 1913

Answers (3)

Adam
Adam

Reputation: 2440

It's literally exactly as it would be without the specific combination of AND/OR. Just use parentheses as necessary.

var query = from table in tables //or whatever your IEnumerable set is if you have one
where table.column1 == value || (table.column2 == value && table.column3 == value)
select table

Upvotes: 1

ocuenca
ocuenca

Reputation: 39326

If you are using Enity Framework and you have an entity with those properties you can do mostly the same using Linq to Entities:

var query= from row in context.Table
           where row.Column1 == "A" || (row.Column2 == "A" && row.Column3 == "A")
           select row;

Also, if you don't want to use LINQ to Entities and you want to execute directly your query, you can use the DbSet.SqlQuery method:

var result=context.Table.SqlQuery("Select * From Table Where Column1 = 'A' OR (Column2 = 'A' AND  Column3 = 'A')");

Upvotes: 1

Nikolai Samteladze
Nikolai Samteladze

Reputation: 7797

Using LINQ extension methods for IEnumerable:

var result = collection.Where(x => x.Column1 = "A" || 
                                  (x.Column2 == "A" && x.Column3 == "A"));

If you are using Entity Framework the you can get filtered results from your table like this:

using (var context = new MyDbContext())
{
    var result = cocontext.MyTable.Where(x => x.Column1 = "A" || 
                                             (x.Column2 == "A" && x.Column3 == "A"));    
}

Upvotes: 5

Related Questions