Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can LINQ ForEach have if statement?

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

sequence.Where(x => x.Name.ToString().Equals("Apple"))         .ToList()         .ForEach( /* If statement here */ ); 
like image 621
abc cba Avatar asked Jul 04 '13 03:07

abc cba


People also ask

Which is better foreach or LINQ?

Most of the times, LINQ will be a bit slower because it introduces overhead. Do not use LINQ if you care much about performance. Use LINQ because you want shorter better readable and maintainable code. So your experience is that LINQ is faster and makes code harder to read and to maintain?

Is LINQ faster than for loop?

At 3M elements, the LINQ implementation takes about 4 milliseconds longer than for/foreach.

Which one is faster for or foreach in C#?

The forloop is faster than the foreach loop if the array must only be accessed once per iteration.


2 Answers

you can do the following...

List.Where(x => x.Name.ToString().Equals("Apple").ToList()     .ForEach( x => { if(x.Name == ""){}} ); 
like image 129
Keith Nicholas Avatar answered Sep 19 '22 14:09

Keith Nicholas


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.        }        }); 
like image 32
tariq Avatar answered Sep 20 '22 14:09

tariq