Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multi-line foreach loop in linq / lambda

I am looking for a way to change the following code:

foreach (Contact _contact in contacts) {     _contact.ID = 0;     _contact.GroupID = 0;     _contact.CompanyID = 0; } 

I would like to change this using LINQ / lambda into something similar to:

contacts.ForEach(c => c.ID = 0; c.GroupID = 0; c.CompanyID = 0); 

However that doesn't work. Is there any way to do multi-line in a linq foreach other than by writing a function to do this in one line?

like image 545
Seph Avatar asked Oct 17 '10 02:10

Seph


1 Answers

contacts.ForEach(c => { c.ID = 0; c.GroupID = 0; c.CompanyID = 0; }); 

It doesn't have anything to do with LINQ per se; it's just a simple anonymous method written in lambda syntax passed to the List<T>.ForEach function (which existed since 2.0, before LINQ).

like image 135
mmx Avatar answered Sep 21 '22 17:09

mmx