Does FirstOrDefault return a reference to an item in a collection or value?

Does FirstOrDefault return a reference to an item in the collection or the value of an item?

var obj = myCollection.FirstOrDefault(x => x.Param == "match condition"); if (obj != null) { obj = newObjectOfCollectionType; //if found, replace with the changed record } 

Will this code replace the object reference in myCollection with a new object, or will it not do anything for myCollection?

+6
source share
4 answers

he will not do anything; obj is a reference to an object (if the collection has 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 an object, it depends on the type of your collection.
If it is IEnumerable<T> , then it is not changed, and you cannot change it.
The best option you have is to create a new collection and change it, for example so-

 T [] array = myCollection.ToArray(); array[index] = newObject; 
+4
source

You can change the collection as follows:

 int index = myCollection.FindIndex(x => x.Param == "match condition"); if (index != -1) { myCollection[index] = newObjectOfCollectionType; } 
+4
source

Returns the value specified in the collection. But this value, in your case, is a link.

It does not return a position. Your code will not change the collection.

+2
source

If the sequence is a sequence of reference types, the reference is returned. Otherwise, the value is returned.

But, in any case, this line:

 obj = newObjectOfCollectionType 

does nothing with the contents of the sequence, regardless of the type of element in the sequence.

+1
source

All Articles