LINQ FirstOrDefault check for default value

前端 未结 2 978
北海茫月
北海茫月 2021-02-11 13:31

How can you check to see whether the object returned by the FirstOrDefault LINQ function is in fact the default?

For example:

Contact conta         


        
相关标签:
2条回答
  • 2021-02-11 14:13

    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.

    0 讨论(0)
  • 2021-02-11 14:21

    FirstOrDefault will return null for reference types and default for value types. Thus your test is invalid. In orther to check wheteher the value is default, you should compare it with default (Type):

    Contact contact = dbo.contact.FirstOrDefault(m => m.contactName == "Stackoverflow");
    
    if (!object.Equals(contact, default (Contact)))
        // Is not default
    

    The code above will work with either struct Contact or class Contact. We also assume that default (Contact) is never a valid return value of our query.

    0 讨论(0)
提交回复
热议问题