Is an object still connected to a list after FirstOrDefault?

linq firstordefault
firstordefault default value
difference between first and firstordefault and singleordefault in linq
firstordefault() in linq query c#
firstordefault vs first
select item from list using linq c#
linq where in list of objects
c# linq select from list of objects

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"?

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.

FirstOrDefault after OrderBy invokes predicate for every element , You can simply combine the conditions inside the FirstOrDefault() like PersonResultList = PersonResultList .Where(pr => PersonList .FirstOrDefault(p = > pr. Dim months As New List(Of Integer)(New Integer() {}) ' Setting the default value to 1 after the query. Dim firstMonth1 As Integer = months.FirstOrDefault() If firstMonth1 = 0 Then firstMonth1 = 1 End If Console.WriteLine($"The value of the firstMonth1 variable is {firstMonth1}") ' Setting the default value to 1 by using DefaultIfEmpty() in the

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.

LINQ query that filters elements from a list of object, List<int> months = new List<int> { }; // Setting the default value to 1 after the query . int firstMonth1 = months.FirstOrDefault(); if (firstMonth1 == 0) { firstMonth1 = 1; }� The FirstOrDefault method will appear in Visual Studio's IntelliSense feature by typing the period after an identifier that describes a type that implements IEnumerable.LINQ. Info: FirstOrDefault is invoked 4 times. The first time the method is invoked, it returns the value of the first string element in the List.

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

Enumerable.FirstOrDefault Method (System.Linq), LINQ Single vs SingleOrDefault vs First vs FirstOrDefault Exception thrown when, There are 0 or more than 1 elements in the In my examples, my employee object did not have a default value, Take a list of integers for example. around the internet, even if they arent linked to us, by linking to them. First() and FirstOrDefault() are two extension methods of the Enumerable class. Extension method is a static method that we can call from an instance object which implement IEnumerable interface. Lets make an analysis of the following simple example.

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.

LINQ Single vs SingleOrDefault vs First vs FirstOrDefault, When using FirstOrDefault, if no value has been found, the default value for this type will be If a few lines of code are simply connected with rewriting properties , using a mapper is still a good choice (mappers enable defining the rules of If you know that a certain object should be disposed after performing some� We have a bit of code to reserve an account from an available pool, which looks like this: var account = accounts.OrderBy(x => x.UsageCount).FirstOrDefault(x => x.TryReserve(token)); After porting our code from .NET Framework to .NET Cor

8 Most common mistakes C# developers make, The First , and FirstOrDefault methods are intended to be used to return one result from Queries for retrieving values relating to multiple objects are only executed Data is iterated over when you use a foreach loop, or a finalising method on the string ProductName { get; set; }; }; List<ProductHeader> headers = context. Equals(Object) Determines whether the specified object is equal to the current object. (Inherited from Object) GetEnumerator() Returns an enumerator that iterates through the query results. GetHashCode() Serves as the default hash function. (Inherited from Object) GetNextResult<TElement>() Gets the next result set of a stored procedure.

Querying data via the DbSet, FirstOrDefault which returns null if it doesn't find anything (but you still need for the variable tweak to be an object (not null)). Comment. Add� Tip. EF Core can only track one instance of any entity with a given primary key value. The best way to avoid this being an issue is to use a short-lived context for each unit-of-work such that the context starts empty, has entities attached to it, saves those entities, and then the context is disposed and discarded.

How to stop .First crashing if it finds nothing?, Many still think, though, that because of the similarity between LINQ keywords and SQL When the C# compiler encounters a method call on an instance of an object, and heap based priority queues, hash indexed array lists, linked lists, and much more. FirstOrDefault(); // returns null/default value if sequence is empty. FirstOrDefault operator. The FirstOrDefault operator returns the first element of a sequence, or a default value if no element is found. Example1. This example defines the FirstOrDefault operator with a integer array without element then it will return 0 value.

Comments
  • Thanks! (blah de blah blah to get to 15 characters ...)
  • Cynthia couldn't upvote you (3 rep). I'm doing this for her =).
  • Hmmmm ... but if it's a reference to the same object, then the list would be changed, would it not? At least, in terms of that object -- not in terms of some element having been added or removed from the list.
  • The list is not changed. The same objects are still in the list after calling FirstOrDefault(). But yes, it it possible to modify a list element via the returned reference (again, assuming Event is a class rather than a struct). This is a characteristic of .NET references, not anything inherent to lists or FirstOrDefault: similarly, if you wrote Event thatEvent = thisEvent;, then changes made to the object through the thatEvent reference would also be seen through the thisEvent reference. One object, multiple references.
  • It is hardly what happens in this case but for the sake of completeness take a look at this question (stackoverflow.com/questions/4052204/…). It shows a possible scenario where FirstOrDefault() looks like disconnected (it was not. actually IEnumerable items were recreated when IEnumerable's source was a "yield return").