views:

311

answers:

1

I have this LINQ statement

Dim Demo = From d In DBDataTable.AsEnumerable _                 
     Select    id = d.Field(Of Integer)("id"), _
            Colun = 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 ?

+1  A: 

[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)
Heinzi