How can you check to see whether the object returned by the FirstOrDefault
LINQ function is in fact the default?
For example:
Contact contact = dbo.contact .Where(m => m.contactName == "Stackoverflow") .FirstOrDefault();
Is there an alternative way to check whether the contact above is default value instead of using the following?
if (!contact.contactName.Equals("Stackoverflow")) // do something
The default value for reference and nullable types is null . The FirstOrDefault method does not provide a way to specify a default value. If you want to specify a default value other than default(TSource) , use the DefaultIfEmpty<TSource>(IEnumerable<TSource>, TSource) method as described in the Example section.
Use the FirstorDefault() method to return the first element of a sequence or a default value if element isn't there. List<double> val = new List<double> { }; Now, we cannot display the first element, since it is an empty collection.
LINQ check if FirstOrDefault is null and use it Just call .... Any(a => a. DateReturned == null)... to check whether there are any items that meet the condition.... If you only want to check the latest assignment, add ....Take(1)...
The major difference between First and FirstOrDefault is that First() will throw an exception if there is no result data for the supplied criteria whereas FirstOrDefault() returns a default value (null) if there is no result data.
You wouldn't need to perform that equals check because your query only returns objects where the contantName is Stackoverflow
. When you use FirstOrDefault
it returns null
if no objects were found so you can do
if(contact == null) do something
You know it's a reference type if Contact is a class so it's default value would be null. You can, however, check it's the default type of any object (reference or value) by using default
.
if(contact == default(Contact)) do something
As mentioned in the comments, you can possibly make your code more efficient by using the overload of FirstOrDefault
that takes a predicate.
FirstOrDefault(m => m.contactName == "Stackoverflow")
You can also change the default value returned if your program needs to work with something other than a null
or 0
. For example
Contact defaultContact = new Contact(); defaultContact.ContactName = "StackExchange"; Contact contact = dbo.contact.Where(m=>m.contactName == "Stackoverflow") .DefaultIfEmpty(defaultContact).First();
The above will return the defaultContact
object if no other object was found (instead of returning null). If you do this then you don't need to check for null
or default(T)
because you know you have a Contact
object.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With