When to use .First and when to use .FirstOrDefault with LINQ?
When to use .First and when to use .FirstOrDefault with LINQ?
I completed my post-graduation in 2013 in the engineering field. Engineering is the application of science and math to solve problems. Engineers figure out how things work and find practical uses for scientific discoveries. Scientists and inventors often get the credit for innovations that advance the human condition, but it is engineers who are instrumental in making those innovations available to the world. I love pet animals such as dogs, cats, etc.
Aryan Kumar
18-Aug-2023The
First()andFirstOrDefault()methods in LINQ are both used to return the first element of a sequence. The difference between the two methods is thatFirst()will throw an exception if the sequence is empty, whileFirstOrDefault()will return the default value of the sequence's type if the sequence is empty.Here is an example of how to use the
First()method:C#
In this code, the
First()method returns the first element of thenumberslist, which is 10.Here is an example of how to use the
FirstOrDefault()method:C#
In this code, the
FirstOrDefault()method returns the first element of thenumberslist, which isnullbecause the list is empty.So, when should you use
First()and when should you useFirstOrDefault()?First()when you are sure that the sequence will not be empty.FirstOrDefault()when you are not sure whether the sequence will be empty.In general, it is better to use
FirstOrDefault()because it is more robust. If you useFirst()and the sequence is empty, your code will throw an exception. This can cause your program to crash.However, if you use
FirstOrDefault()and the sequence is empty, your code will simply return the default value of the sequence's type. This is usually a harmless outcome.