Is it not allowed to have a conditional operator in a lambda expression in ForEach?
List<string> items = new List<string>{"Item 1", "Item 2", "Item I Care About"};
string whatICareAbout = "";
// doesn't compile :(
items.ForEach(item => item.Contains("I Care About") ?
whatICareAbout += item + "," : whatICareAbout += "");
Compilation error -> "Only assignment, call, increment, decrement, and new object expressions can be used as a statement"
Trying to use a normal if doesn't work either:
// :(
items.ForEach(item => if (item.Contains("I Care About")) {whatICareAbout += item + ", ";}
Just not possible?
use of ternary operator in lambda expression gives incorrect results.
In Java 8, it is also possible for the body of a lambda expression to be a complex expression or statement, which means a lambda expression consisting of more than one line. In that case, the semicolons are necessary. If the lambda expression returns a result then the return keyword is also required.
In lambda expressions, the lambda operator => separates the input parameters on the left side from the lambda body on the right side.
The '=>' is the lambda operator which is used in all lambda expressions. The Lambda expression is divided into two parts, the left side is the input and the right is the expression. The Lambda Expressions can be of two types: Expression Lambda: Consists of the input and the expression.
You're using the shorter form of lambda expressions, which only allow a single expressions.
You need to the long form, which allows multiple statements.
For example:
items.ForEach(item => {
if (item.Contains("I Care About"))
whatICareAbout += item + ", ";
});
What are you trying to acheive? Are you trying to form a string of comma separated items where they contain a particular value? In linq you would achieve this using the following:
List<string> items = new List<string> { "Item 1", "Item 2", "Item I Care About", "Item I Care About", "Item I Care About" };
string whatICareAbout = items.Where(x => x.Contains("I Care About"))
.Aggregate( (y, z) => y + ", " + z);
The output from this is "Item I Care About, Item I Care About, Item I Care About".
Note: Aggregate is a great way of ensuring there is no trailing ","
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With