开发者

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

I have this LINQ-开发者_如何学Pythonquery:

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


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


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;


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜