39

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

sequence.Where(x => x.Name.ToString().Equals("Apple"))
        .ToList()
        .ForEach( /* If statement here */ );
3
  • 1
    The question isn't clear
    – zerkms
    Jul 4, 2013 at 3:26
  • 10
    There is no LINQ ForEach method. That is a method of List.
    – user203570
    Jul 4, 2013 at 3:31
  • 2
    What would you want to put in the if that can't be used as predicate in the Where? Jul 4, 2013 at 8:46

4 Answers 4

82

you can do the following...

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

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.
       }  
     });
3

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

2
  • I wouldn't say any... There are some constructs that the expression API cannot represent. Jul 4, 2013 at 5:04
  • 2
    Oh wait sorry, my comment doesn't apply here. We're creating a delegate here, not an expression. IIRC, the same restrictions doesn't affect delegates, any construct may be used. Jul 4, 2013 at 5:19
2

Old thread but throwing an in my opinion cleaner syntax

foreach(var item in sequence.Where(s => s.Name.ToString() == "Apple"))
{
 // do whatever
}
2
  • True, Linq vs traditional foreach should be used for the sake of simplicity, i.e Whatever looks cleaner and easier to understand should be used. Sep 2, 2021 at 5:32
  • If Linq with lambda could shrink long foreach to single line it can be used. But if Linq is becoming too unreadable then traditional foreach can be used for better readability. Sep 2, 2021 at 5:33

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.