Search code examples
.netvb.netlinqcoalesce

Linq Query from textboxes that might be empty (Coalesce)


I need to know if there is any way to coalesce this fields :

String Field1

Integer Field2

When user input is nothing on the textboxes, I need this query to ignore the values but I dont know how to achieve it.

I used Nothing, default nullable value for integer using:

Dim nullInt As Integer?
        nullInt.GetValueOrDefault()

With no luck.

Dim veh As wsTarificador.Class1() =
    (From m In vehiculos
     Where m.Field1= IIf(String.IsNullOrEmpty(txtCaballos.Text), nothing, txtCaballos.Text) _
     And m.Field2=Convert.ToInt32(IIf(String.IsNullOrEmpty(txtPuertas.Text), nothing, txtPuertas.Text))
    Select m).ToArray

Solution

  • Try something like this

    Dim veh As wsTarificador.Class1() =
        (From m In vehiculos
         Where (String.IsNullOrEmpty(txtCaballos.Text) OrElse m.Field1 = txtCaballos.Text) _
         AndAlso (String.IsNullOrEmpty(txtPuertas.Text) OrElse m.Field2=Convert.ToInt32(txtPuertas.Text))
        Select m).ToArray