Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# update object in list

I have a repository with a public List<someView> list; Is it not possible to get an item with linq like this and just update/replace the whole object so the object in the list is updated globally right away?

...
var item = list.SingleOrDefault(m => m.Id== viewModel.Id);
if (item != null)
{
    item = viewModel;
}
...
like image 432
stibay Avatar asked May 30 '17 12:05

stibay


1 Answers

No because item is just a local variable, but you can use the indexer of the list:

int index = list.FindIndex(m => m.Id == viewModel.Id);
if(index >= 0)
    list[index] = viewModel;
like image 75
Tim Schmelter Avatar answered Oct 20 '22 16:10

Tim Schmelter