views:

90

answers:

3

Hey!

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...

+4  A: 
where (a == null || i.IsA == a) &&
      (b == null || i.IsB == b) &&
      (c == null || i.IsC == c)
Mehrdad Afshari
Ah, of course! Thanks.
Mickel
+3  A: 

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;
David M
+1  A: 

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.

Jason
personally I think (a == null || i.IsA == a) is more readable than (a == null ? true : i.IsA == a)
AdamRalph
Perhaps it's more readable because it's shorter but I don't think it most clearly expresses the intent of the code. Of course, this is rather subjective.
Jason