IEnumerable Update At Index

Viewed 22

I have to update a value in the IEnumerable collection. Because it is read only, what is the trick to update the values?

product.Variants is an IEnumerable and I want to update something like this

product.Variants[0].Barcode ="something"

current I get an error like this

enter image description here

then I pass product variable to a function and that does some processing on product.Variants

someFunction (product) // this function should have the new barcode updated above.

1 Answers

Error CS0021 documentation says:

An attempt was made to access a value through an indexer on a data type that does not support Indexers.

Simple as that. An IEnumerable just exposes the enumerator not the underlying data. If you want to access that data you need to "materialize" the IEnumerable into a collection of its data.

var list = product.Variants.ToList();
if(list.Count > 0)
{
    ProductVariant pv = list[0];
    ....
}

but this "materializes" the whole list and if you need only the first item probably you can just use the IEnumerable extension FirstOrDefault;

var pv = product.Variants.FirstOrDefault();
if(pv != null)
{
   .....
}
Related