views:

59

answers:

2

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?

+3  A: 
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).

Mehrdad Afshari
+1  A: 

LINQ stands for Language Integrated Query - which means it is intended for querying - i.e. extracting or transforming a sequence into a new set, not manipulating the original.

The ForEach method hangs off List<T> and is a convenience shortcut to foreach; nothing special.

Rex M