If-else is equivalent to querying linq-to-sql in where, where C #

Basically, I wanted to have an if-else statement in my linq for the sql statement.

var query = from d in database
            if(x == y) {
                where d.Attr = x
            }
            else {
                 where d.Attr = y
            }
            select d;

Any ideas?

+3
source share
6 answers

Isn't it like that

var query = from d in database
            where d.Attr == y
            select d;

Your situation (or a similar, more realistic one) can be handled with a simple conditional where clause. For more complex queries, you can use extension methods to simplify the creation of query execution conditions or use PredicateBuilder to create arbitrarily complex conditions.

var query = db.Table;
if (x == y)
{
   query = query.Where( d.Attr == z );
}
else
{
   query = query.Where( d.Attr == t );
}

var predicate = PredicateBuilder.True<Foo>()
                                .And( f => f.Attr == y )
                                .And( f => f.Attr == x )
                                .Or( f => f.Attr == z );
var query = db.Foo.Where( predicate );
+7
source

Suppose you had in mind ==, and not =:

from d in database
where (x == y && d.Attr == x) ||
      (x != y && d.Attr == y)
select d;
+8

EDIT: , , , , .

, ? () Linq SQL, :

from d in database select (x == y) ? x : y
0

if(x == y) { 
                where d.Attr = x 
            } 

,

if(x == y) { 
                where d.Attr = y 
            } 

x == y?

where d.Attr = y
0
source

This is a solution, assuming you meant ==, not =:

var query = from d in database
            where (x == y ? d.Attr == x : d.Attr == y)
            select d;

However, this is logically equal to the following:

var query = from d in database
            where d.Attr == y
            select d;

Because, if x == ytrue, then d.Attr == xthey d.Attr == y will be equal.

0
source

var query = from d in the database, where (x == y)? d.Attr = x: d.Attr = y select d;

0
source

Source: https://habr.com/ru/post/1746628/


All Articles