Search code examples
vb.netlinqlinq-to-entitieslinq-to-objects

How to use If statement during select from Linq to Datasets


I have this LINQ statement

Dim Demo = From d In DBDataTable.AsEnumerable _                 
     Select id = d.Field(Of Integer)("id"), _
            Column = d.Field(Of Object)  (_column2), _
            Col3 = d.Field(Of Object)(_column3), _
            Col4 = IIf(_Col4 <> -1, d.Field(Of Object)(_Col4), Nothing)

Is there any way that I can use if/iif within select ?


Solution

  • [This is a summary of the discussion in the question comments.]

    Your code won't work since IIf always evaluates both the true and the false part. Thus, evaluating d.Field(Of Object)(_Col4) will raise an exception if _Col4 = -1.

    Instead, use If(condition, true, false), which works like C#'s condition ? true : false operator and only evaluates either the true or the false part, depending on condition. So, your code should read:

    Dim Demo = From d In DBDataTable.AsEnumerable _
               Select id = d.Field(Of Integer)("id"), _
                      Col2 = d.Field(Of Object)(_column2), _
                      Col3 = d.Field(Of Object)(_column3), _
                      Col4 = If(_Col4 <> -1, d.Field(Of Object)(_Col4), Nothing)