FirstOrDefault是否返回对集合中项目的引用或值?

tra*_*ber 9 c# linq

FirstOrDefault是否返回对集合中项目的引用或项目的值?

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

这个代码会用新对象替换myCollection中的对象引用,还是对myCollection什么都不做?

小智 10

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
}
Run Code Online (Sandbox Code Playgroud)


dis*_*scy 8

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;
}
Run Code Online (Sandbox Code Playgroud)


J. *_* Ed 5

它什么也不做;obj 是对对象的引用(如果集合是引用类型),而不是对象本身。
如果集合是原始类型,则 obj 将是集合中值的副本,并且再次 - 这意味着集合不会改变。

编辑:
要替换对象,这取决于您的集合类型。
如果是IEnumerable<T>,则它不可变,您将无法更改它。
您拥有的最佳选择是创建一个新集合并对其进行修改,如下所示-

T [] array = myCollection.ToArray();
array[index] = newObject;
Run Code Online (Sandbox Code Playgroud)