views:

65

answers:

2

Hello,

I have this code

foreach (MyType o in myList)
{
    var res = from p in myOriginalList
        where p.PropertyA == o.PropertyA && p.PropertyB == o.PropertyB
        select p;

    //Need to update myOriginalList

    //....
}

I'd like in the myOriginalList do an update for each record found by the Linq select. How can I do this ?

Thanks,

A: 
foreach(var item in res)
{
   item.prop = updatedvalue;
}

Do you mean this?

ArsenMkrt
+1  A: 

There is no inbuilt ForEach extension - so just loop and update:

foreach(var item in res) {
    item.SomeProp = someValue;
}

Note also that you can use SelectMany to do this in one query:

var res = from MyType o in myList
          from p in myOriginalList
              where p.PropertyA == o.PropertyA && p.PropertyB == o.PropertyB
              select p;
Marc Gravell
To be nitpicky, there is a ForEach extension, but not directly on the IEnumerable interface but on the generic List (philosophic reasons: http://stackoverflow.com/questions/800151/why-is-foreach-on-ilistt-and-not-on-ienumerablet/1296774#1296774)
Marc Wittke
Oh, I'm very much aware of them ;-p But cheers.
Marc Gravell
in the first part, you update the result of the query not "myOriginalList" right ? it's an update of the original based on the res result I need
Kris-I
@Kris-I; it depends on what you are trying to do. Normally when people say "update the list" they mean "update the state of the objects that are referenced by the list", i.e. "item.SomeProp = someValue;". Unless you are using `struct`s. Do you mean to *swap* items in the list? i.e. change the actual reference?
Marc Gravell