notAnonymousAnymore
notAnonymousAnymore

Reputation: 2687

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

But invoices.Where(l => l.OrganisationID == part.OrganisationID) might be null, in which case id needs to be a new Nullable<int>.

How can I do this in one line (and efficiently) rather than first checking if the object is null or not?

Upvotes: 2

Views: 8053

Answers (1)

Andrzej Gis
Andrzej Gis

Reputation: 14316

How about that?

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

Upvotes: 1

Related Questions