LINQ FirstOrDefault check for default value

前端 未结 2 981
北海茫月
北海茫月 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.

提交回复
热议问题