views:

25

answers:

0

Here is my code: I thought using DLink I should be able to pass the where clause as string expressions however the FindFirstOrDefault doesn't work. Basically, I want the FindFirstOrDefault to be generic so I can pass any object, its key property and value and it should find it. Any ideas?

<TestMethod()> Public Sub TestExpression()
    Dim loList As New List(Of MyProduct)
    With loList
        .Add(New MyProduct With {.ProductID = 1, .ProductName = "P1", .ProductCategory = "Tea"})
        .Add(New MyProduct With {.ProductId = 2, .ProductName = "P2", .ProductCategory = "Tea"})
        .Add(New MyProduct With {.ProductId = 1, .ProductName = "P3", .ProductCategory = "Coffee"})
    End With
    ' get a product by id and type - work ok
    Dim productToFind = (From product In loList Where product.ProductId = 1 _
                         And product.ProductCategory = "Tea" _
                        Select product).FirstOrDefault
    Assert.AreEqual("P1", productToFind.ProductName)

    ' or  - work ok
    productToFind = loList.FirstOrDefault(Function(p As MyProduct) p.ProductId = 1)
    Assert.AreEqual("P1", productToFind.ProductName)

    ' or - find it dynamically by key property and value so could be product, service, person etc
    Dim AllProducts = From allList In loList
    Dim dynamicItem = FindFirstOrDefault(Of MyProduct)(AllProducts, 1, "ProductID")
    Assert.AreEqual("P1", dynamicItem.ProductName)

    'dynamicItem = FindFirstOrDefault(Of MyService)(AllServices, 1, "ServiceID")
    'Assert.AreEqual("S1", dynamicItem.ServiceName)

End Sub


Private Function FindFirstOrDefault(Of t As Class)(ByVal list As IEnumerable(Of t), _
                                              ByVal keyPropertyValue As Object, _
                                              ByVal keyPropertyName As String)
    Dim lsCondition As String = keyPropertyName + "=" + keyPropertyValue.ToString
    Dim itemToFind As t = (From i In list Where lsCondition).FirstOrDefault
    Return itemToFind
End Function

Class MyProduct
    Private msProductId As String
    Public Property ProductId() As String
        Get
            Return msProductId
        End Get
        Set(ByVal value As String)
            msProductId = value
        End Set
    End Property


    Private msProductName As String
    Public Property ProductName() As String
        Get
            Return msProductName
        End Get
        Set(ByVal value As String)
            msProductName = value
        End Set
    End Property


    Private msProdCat As String
    Public Property ProductCategory() As String
        Get
            Return msProdCat
        End Get
        Set(ByVal value As String)
            msProdCat = value
        End Set
    End Property
End Class