Search code examples
c#delegatesanonymous-methods

Can we update a list using anonymous methods?


I have a list (MyList) of objects...and I would like to update one property (Priority) of each item in that list.

Will the below code work for that ?

this.MyList.All(
    delegate(ItemViewModel itemObject)
    {   
        itemObject.Priority = priority++;
    }
)

Please help me. Thanks in advance!


Solution

  • Why not just use foreach?

    foreach(ItemViewModel itemObject in MyList)
      itemObject.Priority = priority++;
    

    If you really want to use a delegate you can use ForEach():

    MyList.ForEach(itemObject =>
    {
        itemObject.Priority = priority++;
    });
    

    This is not advisable though since you introduce a side effect with priority++