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;
}
}
To update or set an element or object at a given index of Java ArrayList, use ArrayList. set() method. ArrayList. set(index, element) method updates the element of ArrayList at specified index with given element.
A collection is a class, so you must declare an instance of the class before you can add elements to that collection. If your collection contains elements of only one data type, you can use one of the classes in the System. Collections. Generic namespace.
Collection classes serve various purposes, such as allocating memory dynamically to elements and accessing a list of items on the basis of an index etc. These classes create collections of objects of the Object class, which is the base class for all data types in C#.
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.
var productToUpdate = this.ProductSearchResults.FirstOrDefault(p => p.ID == product.ID);
if (productUpdate != null)
{
productUpdate.Property = product.Property;
...continue for other properties
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With