LINQ FirstOrDefault检查默认值 [英] LINQ FirstOrDefault check for default value
问题描述
如何检查FirstOrDefault
LINQ函数返回的对象是否实际上是默认对象?
How can you check to see whether the object returned by the FirstOrDefault
LINQ function is in fact the default?
例如:
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
推荐答案
您不需要执行相等检查,因为您的查询仅返回contantName为Stackoverflow
的对象.当您使用FirstOrDefault
时,如果未找到任何对象,它将返回null
,您可以这样做
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
如果Contact是一个类,您知道它是引用类型,因此其默认值将为null.但是,您可以使用default
检查它是任何对象(引用或值)的默认类型.
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
如注释中所述,您可以通过使用带谓词的FirstOrDefault
重载来提高代码的效率.
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")
如果程序需要与null
或0
以外的其他程序一起使用,则还可以更改返回的默认值.例如
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();
如果未找到其他对象,则以上内容将返回defaultContact
对象(而不是返回null).如果执行此操作,则无需检查null
或default(T)
,因为您知道自己有一个Contact
对象.
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.
这篇关于LINQ FirstOrDefault检查默认值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!