user1418704 user1418704 - 8 days ago 5
C# Question

LINQ: Set a default value if navigation property is null

This is my current LINQ statement:

var results = from l in leads
select new MyObject
{
LeadID = l.LeadID,
SelectedProposalEngineerID = l.LeadContacts.Where(contact => contact.LeadContactTypeID == LeadContactType.ProposalEngineer).FirstOrDefault().ContactID
};


The trouble I'm having is that the last item is often null. So when I try to convert "results" to a List, I get


{"The cast to value type 'System.Int32' failed because the materialized value is null. Either the result type's generic parameter or the query must use a nullable type."}


I don't want to make SelectedProposalEngineerID a nullable int, for problems that would cause down stream. How would I give it a value of 0 when it's null?

I have seen a LOT of other threads about this, but I can't seem to adapt any of their answers to this case.

Answer

Use DefaultIfEmpty extension method.

var results = from l in leads
    select new MyObject
    {
        LeadID = l.LeadID,
        SelectedProposalEngineerID = 
            l.LeadContacts.Where(contact => contact.LeadContactTypeID == LeadContactType.ProposalEngineer)
                          .Select(contact => contact.ContactID)
                          .DefaultIfEmpty(0)
                          .FirstOrDefault()
    };
Comments