none
Conditional statement in LINQ - checking for null RRS feed

  • Question

  • Hi all,

    nood to linq.... so bare with me.  I have the following snippet of code using LINQ to create an enumeration of Contracts from a dataset.

    IEnumerable<Contract> contracts = (from row in ds.contract
    select new Contract
    {
    CreatedTime = row.sale_date,
    Number = row.contract_id,
    Salesperson = row.salesName
    InvoiceNumber = row.invoice_id});
    

    The problem I have is that some values (ie  invoice_id) may sometimes be null.  I would prefer to have invoice_id come back as a nullible int, but that is out of my control.  So I have to do some sort of check... and if I was doing a standard iteration instead of LINQ... I'd do something like:

    if (row.Isinvoice_idNull())
    
    {
    
    
    
    		 //is null
    
    		 InvoiceNumber = -1;
    
    }
    
    else
    
    {
    
    		 //is not null
    
    		 InvoiceNumber = row.invoice_id;
    
    }
    
    
    
    
    
    

    Thanks in advance!

    Monday, February 7, 2011 4:36 PM

Answers

All replies

  • This seems to work:

     

    InvoiceNumber =row.Isinvoice_idNull()?

    null:(int?)row.invoice_id

     

     

    Monday, February 7, 2011 9:46 PM
  • Yes, generally we will use the conditional operator.  Thanks for sharing the solution here.
    http://msdn.microsoft.com/en-us/library/ty67wk28(v=VS.100).aspx

    =============================================================
    IEnumerable<Contract> contracts = (from row in ds.contract
                                                           select new Contract
                                                          {
                                                               CreatedTime = row.sale_date,
                                                               Number = row.contract_id,
                                                               Salesperson = row.salesName
                                                               InvoiceNumber = row.Isinvoice_idNull() ? null : (int?)row.invoice_id
                                                           });
    =============================================================

    Good day!

    Thanks


    Michael Sun [MSFT]
    MSDN Community Support | Feedback to us
    Get or Request Code Sample from Microsoft
    Please remember to mark the replies as answers if they help and unmark them if they provide no help.

    Tuesday, February 8, 2011 3:06 AM
    Moderator