views:

46

answers:

3

Friends,

I know how to deploy and retrieve a single element in LINQ, but how can I do to change all the properties in a list. In the line below, I can only modify a record, I would modify several.

_ListaAcaoMenuInfo.Where(p => p.Id_acao == id).FirstOrDefault().Id_menu = 0;

Thanks

+1  A: 

Use foreach:

var l = _ListaAcaoMenuInfo.Where(p => p.Id_acao == id).ToList();

foreach (Thing i in l)
{
   i.Id_menu = 0;
   //now use your Context object to save back to the database
}
Dave Swersky
+1  A: 

You wouldn't want to. LINQ is not to be used for side effects. There's a foreach loop for that.

foreach (var x in collection.where(x => x.Foo = "Blah"))
   x.Foo = "Bar";
Anthony Pegram
you mean that LINQ should not be directly used to update information, only to get?
Ph.E
well, very thanks!
Ph.E
Right. There's a ForEach method available for List, as others have pointed out, but LINQ itself is for filtering, retrieval, projection, etc. As for using .ForEach instead of a foreach loop, there's a school of thought that the loop is more readable, easier to maintain, etc. But the fact is the method is there to use if you wish.
Anthony Pegram
+5  A: 

Use the ForEach function of a List...

_ListaAcaoMenuInfo.Where(p => p.Id_acao == id).ToList().ForEach(item=>item.Id_menu=0);
ChrisNel52
+1 - I was about to post this exact code. Will this be persist-able back to the database?
hunter
Yes, each entity has had it's Id_menu property changed. The changes will be persisted after calling SaveChanges() on the DataContext.
ChrisNel52
Thanks brother, very useful for me!
Ph.E