.netvb.netlinqlogical-operators

why does the operator logic in Linq not match the results when the value is 0 or nothing in VB.NET


I'm Trying operator logic but in Linq not match the results when the value is 0 or nothing in VB.NET

Let STATUS = If(BLC < 24 And PRSOBNET Is Nothing, "NEED TO PRODUCE", "")

is there something wrong with my code? . Please Guide me.

Dim Cardex =
           From card In PurchaseDetails.Union(SalesDetails)
           Join mst In MasterItem On card.ITEM Equals mst.ITEM
           Group card By card.ITEM, mst.PRODUCTIONNAME, mst.BRAND, mst.PRSOBNET Into Group
           Let PIQ = (From x In Group Select x.PIQ).Sum
           Let SIQ = (From x In Group Select x.SIQ).Sum
           Let BLC = (PIQ) - (SIQ)
           Let STATUS = If(BLC < 24 And PRSOBNET Is Nothing, "NEED TO PRODUCE", "")
           Order By ITEM
           Select New ItemCards2 With {
    .ITEM = ITEM,
    .PRODUCTIONNAME = PRODUCTIONNAME,
    .BRAND = BRAND,
    .PRSOBNET = PRSOBNET,
    .PIQ = If(PIQ <> 0, PIQ, Nothing),
    .SIQ = If(SIQ <> 0, SIQ, Nothing),
    .BLC = If(BLC <> 0, BLC, Nothing),
    .STATUS = STATUS
 bindingSource = New BindingSource With {
    .DataSource = New BindingList(Of ItemCards2)(Cardex.ToList())
        DataGridView1.DataSource = bindingSource


Public Class ItemCards2
    Public Property ITEM As String
    Public Property PRODUCTIONNAME As String
    Public Property BRAND As String
    Public Property PRSOBNET As Integer?
    Public Property PIQ As Integer?
    Public Property SIQ As Integer?
    Public Property BLC As Integer?
    Public Property STATUS As String
End Class

Result in datagridview

Desired Result

ITEM PRODUCTIONNAME BRAND PRSOBNET PIQ SIQ BLC STATUS
1000 A A1 20000 20 27 -7
10000 Z Z1 23 23 NEED TO PRODUCE
2000 B B2 0 2 -2 NEED TO PRODUCE

Solution

  • If you specifically want something to happen when a value is zero then you neeed to specify that. This:

    Let STATUS = If(BLC < 24 And PRSOBNET Is Nothing, "NEED TO PRODUCE", "")
    

    doesn't do that. You even put the solution in the title of your question:

    the value is 0 or nothing in VB.NET

    You have "or" in your title but there's no Or in your code. You know what the logic is but you didn't implement it in code.

    Let STATUS = If(BLC < 24 AndAlso (Not PRSOBNET.HasValue OrElse PRSOBNET.Value = 0), "NEED TO PRODUCE", "")
    

    Note that I used AndAlso and OrElse, which are the short-circuiting Boolean operators. ALWAYS use them is preference to And and Or unless you specifically want to avoid short-circuiting, which should be fairly rare. In this specific case, using And rather than AndAlso would not affect the result but using Or rather than OrElse would generate a NullReferenceException in cases where PRSOBNET.HasValue was False, becaise it would still try to get PRSOBNET.Value. Short-circuiting ensures that the second operand is not evaluated if the the first operand is True.