How can i update an element in collection instead of the reference
c#
Solution
IN actual fact all you are doing is changing the reference to the local variable `toUpdate` to point at the passed-in argument `product`.
Lets take a step backwards, when you do:
var toUpdate = productToUpdate.First<ProductInfo>();
you have a reference to an item from your collection (`ProductSearchResults`). You can now happily update its properties, ala:
toUpdate.ProductName = product.ProductName;
toUpdate.Price = product.Price;
//etc..
however, you cannot update the itemn in the collection to point to a different/new item in the way you were attempting to. You could remove that item from the collection, and add your new one if that is indeed what you require:
public void UpdateProductInfo(ProductInfo product)
{
var productToUpdate = this.ProductSearchResults.Where(p => p.ID == product.ID);
if (productUpdate.Count() > 0)
{
var toUpdate = productToUpdate.First<ProductInfo>();
this.ProductSearchResults.Remove(toUpdate);
this.ProductSearchResults.Add(product);
}
}
Hope that helps.
Problem
I have a collection ProductSearchResults, below method intends to find a specific product in that collection and update it. I end up updating the object that points to the element of the collection instead of the actual element it self though(i think) Can you please show me how to do this properly so that I update the actual product in the collection Thanks ``` public void UpdateProductInfo(ProductInfo product) { var productToUpdate = this.ProductSearchResults.Where(p => p.ID == product.ID); if (productUpdate.Count() > 0) { var toUpdate = productToUpdate.First<ProductInfo>(); toUpdate = product; } } ```