Search code examples
c#vb.netlambdaidatareader

Convert C# lambda function to VB.net


I have this function that maps a IDataReader to a class. It is obviously written in C#. My co-worker wants to use the same method in his code, but he is writing in VB.net. Basically I am having difficulty rewriting this due to the Lambda expressions used in C#. He is running .Net 3.5.

Can anyone help me?

private Func<IDataReader, ScanItem> resultMapper = r =>
    {
        var si = new ScanItem()
        {
            StoreGroupCode = r.ToInt32("GRP_CDE"),
            StoreCode = r.ToInt32("STOR_CDE"),
            EventNumber = r.ToInt32("EVENT_NUM"),
            AreaNumber = r.ToInt32("INV_CTL_AREA_CDE"),
            LabelNumber = r.ToInt32("LBL_NUM"),
            ScanType = r.ToString("INV_SCAN_TYP_IND"),
            SequenceNumber = r.ToInt32("INV_SCAN_SEQ_NUM"),
            UPC = r.ToLong("VEN_UPC_NUM"),
            ActualQuantity = r.ToLong("ACT_CNT_QTY")
        };

        return si;
    };

Solution

  • IIRC VB.NET in .NET 3.5 doesn't support anonymous functions with body. Your co-worker using VB.NET will have to define a function containing this code and in the lambda expression use this function. Now, this being said, it's not really necessary to use a complex function with body in this case and this code could be simplified to:

    private Func<IDataReader, ScanItem> resultMapper = r => new ScanItem
    {
        StoreGroupCode = r.ToInt32("GRP_CDE"),
        StoreCode = r.ToInt32("STOR_CDE"),
        EventNumber = r.ToInt32("EVENT_NUM"),
        AreaNumber = r.ToInt32("INV_CTL_AREA_CDE"),
        LabelNumber = r.ToInt32("LBL_NUM"),
        ScanType = r.ToString("INV_SCAN_TYP_IND"),
        SequenceNumber = r.ToInt32("INV_SCAN_SEQ_NUM"),
        UPC = r.ToLong("VEN_UPC_NUM"),
        ActualQuantity = r.ToLong("ACT_CNT_QTY")
    };
    

    which normally if my VB.NET isn't too rusty should look something along the lines of:

    Private resultMapper As Func(Of IDataReader, ScanItem) = Function(r) New ScanItem() With { _
        .StoreGroupCode = r.ToInt32("GRP_CDE"), _
        .StoreCode = r.ToInt32("STOR_CDE"), _
        .EventNumber = r.ToInt32("EVENT_NUM"), _
        .AreaNumber = r.ToInt32("INV_CTL_AREA_CDE"), _
        .LabelNumber = r.ToInt32("LBL_NUM"), _
        .ScanType = r.ToString("INV_SCAN_TYP_IND"), _
        .SequenceNumber = r.ToInt32("INV_SCAN_SEQ_NUM"), _
        .UPC = r.ToLong("VEN_UPC_NUM"), _
        .ActualQuantity = r.ToLong("ACT_CNT_QTY") _
    }