user1334653
user1334653

Reputation:

LINQ with if statement

My LINQ query returns values if "attribute" is bigger than 0 else it doesn't work and I get no error. I guess the && in the third line wants another statement which it doesn't get if "attribute" isn't bigger than 0. How can I get over this?

Edit: The code I've written first, was doing what abatishchev's answer is saying. I've tried to do a shorthand if statement without else but I've read about that wrong, so the code was meant to do something else then it actualy did. Thank you for the enlightenment on that matter but I still don't know how to implement my initial wish to linq, so I've rearranged the code to something that is nearer to my goal.

int attribute = 0;
var query = from x in db.Table1
            where x.ValueId == 1

            if(attribute > 0)
                x.Table2.Attribute == attribute

            select x;

If attribute is bigger than 0, then I wan't to add an additional where clause to my query.

Thank you for your help.

Upvotes: 0

Views: 3424

Answers (4)

user1334653
user1334653

Reputation:

if (attribute > 0)
   query = query.Where(a => a.Table2.Attribute == attribute);

Upvotes: 0

juharr
juharr

Reputation: 32266

I think you might want to do this

int attribute = 0;
var query = from x in db.Table1
            where (attribute <= 0) ||
            (x.ValueId == 1 &&
            x.Table2.Attribute == attribute)
            select x;

That results in everything in Table1 when the attribute is <= 0. If the attribute is greater than zero then it will apply your filters.

Upvotes: 1

abatishchev
abatishchev

Reputation: 100258

(attribute > 0) && x.Table2.Attribute == attribute

means 'if attribute is greater than 0 and table attribute is equal to given, otherwise skip'

attribute <= 0 || ((attribute > 0) && x.Table2.Attribute == attribute)

means 'if attribute is greater than 0 and table attribute is equal to given, otherwise include'

Upvotes: 4

Honza Brestan
Honza Brestan

Reputation: 10947

If the attribute is not greater than 0, attribute > 0 evaluates as false and because you use it in where filter, no x actually passes that filter and you get an empty enumeration, which is only correct. So the answer is review your logic, re-think what should the attribute mean and how should it affect the query outcome.

Upvotes: 0

Related Questions