0

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,

TheBoubou
  • 19,487
  • 54
  • 148
  • 236

2 Answers2

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

Do you mean this?

Arsen Mkrtchyan
  • 49,896
  • 32
  • 148
  • 184
1

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
  • 1,026,079
  • 266
  • 2,566
  • 2,900
  • 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 Dec 16 '09 at 07:06
  • 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 – TheBoubou Dec 16 '09 at 07:09
  • @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 Dec 16 '09 at 12:41