开发者

Is an object still connected to a list after FirstOrDefault?

He开发者_开发百科re'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"?


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.


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.


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.


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜