简体   繁体   English

if-else通过where子句c#中的linq-to-sql查询等效

[英]if-else equivalent via linq-to-sql query in where clause c#

Basically I wanted to have an if-else statement in my linq to sql statement. 基本上我想在我的linq to sql语句中有一个if-else语句。

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

Any ideas? 有任何想法吗?

Supposing, you meant == and not = : 假设,你的意思是==而不是=

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

Isn't that just the same as 这不是一样的

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 in the where clause. 您可以使用where子句中的简单条件处理您的情况(或类似的,更现实的情况)。 For more complex queries you can use the extension methods to build up a query implementing conditionals pretty easily or use a PredicateBuilder to create arbitrarily complex conditions. 对于更复杂的查询,您可以使用扩展方法来构建非常容易实现条件的查询,或者使用PredicateBuilder来创建任意复杂的条件。

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 );

EDIT: I think I may have misunderstood what you wanted to do. 编辑:我想我可能误解了你想做什么。

I'm not sure if the ? 我不确定是不是? (ternary) operator will work in Linq to SQL, but try this: (三元)运算符将在Linq to SQL中工作,但尝试这样:

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

wouldnt 难道不

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

be the same as 和...一样

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

if x==y? 如果x == y?

so couldnt you just use 所以你不能使用

where d.Attr = y

This is the solution, assuming you meant == and 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 == y is true, then d.Attr == x and d.Attr == y will be equal. 因为,如果x == y为真,则d.Attr == xd.Attr == y 相等。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM