简体   繁体   English

LINQ 如果不为空则选择

[英]LINQ Select if not null

I'm trying to do something like this:我正在尝试做这样的事情:

int? id = invoices.Where(l => l.OrganisationID == part.OrganisationID)
                  .Select(m => m.TypeID).FirstOrDefault();

'invoices' is a List “发票”是一个List

But invoices.Where(l => l.OrganisationID == part.OrganisationID) might be null, in which case id needs to be a new Nullable<int> .但是invoices.Where(l => l.OrganisationID == part.OrganisationID)可能为空,在这种情况下id需要是一个新的Nullable<int>

How can I do this in one line (and efficiently) rather than first checking if the object is null or not?我怎样才能在一行中(并且有效地)做到这一点,而不是首先检查对象是否为空?

How about that?那个怎么样?

int? id = invoices
    .Where(l.OrganisationID == part.OrganisationID))
    .Select(m => m.TypeID as int?) // add 'as int?'
    .FirstOrDefault();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM