Mickel
Mickel

Reputation: 6696

Can the where-condition in this LINQ-query be optimized?

I have this LINQ-query:

            bool? a, b, c;

            from i in _ctx.SomeEntitySet

            where
                (a == null ? true : i.IsA == a) &&
                (b == null ? true : i.IsB == b) &&
                (c == null ? true : i.IsC == c)

            select i;

I only want to take the condition IsX == x into consideration if x != null.

Brainfreeze, please help me out...

Upvotes: 0

Views: 176

Answers (3)

jason
jason

Reputation: 241641

I think the version that you have most clearly expresses the intention. I would not change it.

Alternatives:

a == null || i.IsA == a;

!a.HasValue || i.IsA == a;

i.IsA == (a ?? i.IsA);

None of these is clearer to me, however. Don't focus on efficiency, focus on readability and expressiveness.

Upvotes: 1

David M
David M

Reputation: 72870

Not sure it's any more efficient, but it reads better:

        bool? a, b, c;

        from i in _ctx.SomeEntitySet

        where
            (a == null || i.IsA == a) &&
            (b == null || i.IsB == b) &&
            (c == null || i.IsC == c)

        select i;

Upvotes: 3

Mehrdad Afshari
Mehrdad Afshari

Reputation: 422016

where (a == null || i.IsA == a) &&
      (b == null || i.IsB == b) &&
      (c == null || i.IsC == c)

Upvotes: 4

Related Questions