Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

linq

Does FirstOrDefault return a reference to the item in the collection or the value of the 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 the myCollection with the new object, or will it do nothing to myCollection?

like image 640
trashrobber Avatar asked Apr 04 '13 13:04

trashrobber


2 Answers

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
}
like image 119
Vishal Naidu Avatar answered Nov 08 '22 06:11

Vishal Naidu


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;
}
like image 8
discy Avatar answered Nov 08 '22 08:11

discy