开发者

lambda Expression: Best practice for AND condition inside Where(TSource) Function

Is there any good practice to write AND in lambda expression instated of writing the following IF inside Where() function

lst.Where(obj=> {
  if (obj.Pro开发者_如何学编程p1 == true && obj.Prop2 == true)
    return true;
  return false;
          });


Any reason not to write:

lst.Where(obj => obj.Prop1 && obj.Prop2)

? In general:

  • I avoid direct comparisons with true and false, preferring if (foo) to if (foo == true)
  • When you have a code structure of:

    if (condition)
    {
        return true;
    }
    else
    {
        return false;
    }
    

    then you can just replace it with:

    return condition;
    

    That's just as true in lambda expressions as in anything else - except that with lambda expressions like yours, it means you can move from a statement lambda (braces surrounding the body) to an expression lambda (without braces).

The second point extends beyond just true and false, too, using the conditional operator. I would usually convert this:

if (condition)
{
    return x;
}
else
{
    return y;
}

to

return condition ? x : y;
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜