Search code examples
c#linqexceptiongeneric-collections

NullArgument Exception in LINQ query


The following query can throw a NullArgumentException in some cases, since items inside the m_SelectedPayabes collection can be null. How does the query need to be modified so that it doesn't throw a NullArgumentException when it encounters a null reference?

var myPayables = from payable in m_Payables
where !(from o in m_SelectedPayabes select o.PBLE.PAYABLEID).Contains(payable.PBLE.PAYABLEID)                                     
select payable;

Solution

  • You can either exclude the nulls:

    var myPayables = from payable in m_Payables
                     where !(from o in m_SelectedPayabes 
                             where o != null
                             select o.PBLE.PAYABLEID).Contains(payable.PBLE.PAYABLEID)                                     
                     select payable;
    

    Or replace the nulls with something else (assuming o.PBLE.PAYABLEID is an integer):

    var myPayables = from payable in m_Payables
                     where !(from o in m_SelectedPayabes 
                             select o == null ? 0 : o.PBLE.PAYABLEID).Contains(payable.PBLE.PAYABLEID)                                     
                     select payable;