Is an object still connected to a list after FirstOrDefault?

孤街浪徒 提交于 2019-12-08 15:20:44

问题


Here's my code:

        Event thisEvent = (from i in list
                           where (i.eventID == eventID)
                           select i).FirstOrDefault();
        if (thisEvent != null)
        {
            thisEvent.eventResolved = resolved;
            thisEvent.eventSequence.Add(item);
        }

"list" is a collection of IEnumerable, i.e.

IEnumerable<Event> list;

What I'm wondering is: after creating thisEvent using FirstOrDefault, is thisEvent still connected to list? In other words, when I change the two properties, eventResolved and eventSequence, is "list" actually changed, or is thisEvent just some totally disconnected copy of an item in "list"?


回答1:


FirstOrDefault selects an item in a collection, but does not "detatch" or "clone" it. I.e. it is the same instance. So if you modify a property you modify the original instance.

If you want to "detatch" the object you will have to copy it in some way or the other.




回答2:


list is not changed, and still includes the object returned by FirstOrDefault.

This is a general rule with all the LINQ operators: they never modify the source collection.

Also note that thisEvent is not a "copy" (unless Event is a value type (struct) rather than a class) -- it is a reference to the same object that is referenced in list.




回答3:


If Event is a reference type, then yes, modifying thisEvent will modify the element in the list.




回答4:


Beware, this is true if your collection is in memory. If your collection is the result of a database query, the collection is not materialized until you call ToList on it. If you do FirstOrDefault before that, it will make a query to the database to return only this result and then materializing your collection will make a seperate call to the DB and you will not share the same instance. It just happened to me so I hope this can help someone else.



来源:https://stackoverflow.com/questions/2436388/is-an-object-still-connected-to-a-list-after-firstordefault

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!