Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using conditional operator in lambda expression in ForEach() on a generic List?

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?

like image 684
Jamezor Avatar asked Nov 29 '09 21:11

Jamezor


People also ask

Can we use ternary operator in lambda expression?

use of ternary operator in lambda expression gives incorrect results.

How do you write multiple statements in lambda expression?

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.

What does => mean in lambda?

In lambda expressions, the lambda operator => separates the input parameters on the left side from the lambda body on the right side.

Which is the lambda operator used in all lambda expressions?

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.


2 Answers

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 + ", ";
});
like image 173
SLaks Avatar answered Oct 07 '22 01:10

SLaks


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 ","

like image 29
Matt Breckon Avatar answered Oct 07 '22 01:10

Matt Breckon