LINQ FirstOrDefault check for default value

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

提交回复
热议问题