How can i update an element in collection instead of the reference
var productToUpdate = this.ProductSearchResults.FirstOrDefault(p => p.ID == product.ID);
if (productUpdate != null)
{
productUpdate.Property = product.Property;
...continue for other properties
}
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.