I am trying to improve my skills on lambda expressions.
I have a string[]
args which contains some words. It could contain the word "students" as well. I want to set the boolean doStudents
to true
if the args contains this word.
I have made this statement which works well:
bool doStudents = args.Where(x => x.Contains("students")).Count()>0 ?true:false;
How can I simplify this statement?
You can improve this lambda statement in two ways:
First, you are checking if there is any "students" in the argument x, by counting the number of times it occurs and then comparing it to 0. Actually, you just check if there is any "students" in x.
It would thus be more efficient to write x.Contains("students")).Any();
Secondly, you can omit the last part of your statement. The first part already returns true/false. With the last part, you make doStudents true if the before statement is true, and false if the before statement is false. Obviously, this does not add any information to the statement and should therefore be omitted.
Your new statement would be: bool doStudents = args.Where(x => x.Contains("students")).Any()
.
Note: I first wanted to ask this here, but then I found a way to test it for myself. It worked well, so therefore I made it a Q&A question.