Can LINQ ForEach have if statement?

72,369

Solution 1

you can do the following...

List.Where(x => x.Name.ToString().Equals("Apple").ToList()
    .ForEach( x => { if(x.Name == ""){}} );

Solution 2

Yes, if-statement is commonly used inside the ForEach as below:

sequence.Where(x => x.Name.ToString().Equals("Apple"))
    .ToList()
    .ForEach( x =>
     {
       if(someCondition)
       {
         // Do some stuff here.
       }  
     });

Solution 3

Yes, It takes a lambda expressions, so you can put any valid c# expression in there

Solution 4

Old thread but throwing an in my opinion cleaner syntax

foreach(var item in sequence.Where(s => s.Name.ToString() == "Apple"))
{
 // do whatever
}
Share:
72,369
abc cba
Author by

abc cba

Updated on October 25, 2020

Comments

  • abc cba
    abc cba over 3 years

    Is it possible to add if-statement inside LINQ ForEach call?

    sequence.Where(x => x.Name.ToString().Equals("Apple"))
            .ToList()
            .ForEach( /* If statement here */ );