Does FirstOrDefault return a reference to the item in the collection or the value?
var obj = myCollection.FirstOrDefault(x => x.Param == "match condition");
if (obj != null)
{
obj = newObjectOfCollectionType; --> this will not reflect in the collection
}
var obj = myCollection.FirstOrDefault(x => x.Param == "match condition");
if (obj != null)
{
obj.Property = newValue; --> this will reflect in your object in the original collection
}
It does nothing to the collection. You can change the collection like this:
int index = myCollection.FindIndex(x => x.Param == "match condition");
if (index != -1)
{
myCollection[index] = newObjectOfCollectionType;
}
it will do nothing; obj is a reference to the object (if the collection is of a reference type), and not the object itself.
If the collection is of a primitive type, then obj will be a copy of the value in the collection, and, again- this means that the collection will not change.
Edit:
to replace the object, it depends what your collection's type is.
If it's IEnumerable<T>
, then it's not mutable, and you won't be able to change it.
The best option you have is to create a new collection and modify that, like so-
T [] array = myCollection.ToArray();
array[index] = newObject;