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)
toif (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;
精彩评论