PBMining

Searching...
Thursday, February 16, 2012

Update object using linq

4:22 AM

In this Post I am going to explain the way for updating objects using Linq.Microsoft Linq is generally used for query the memory objects its default functionality does not allow to update any object resides in memory.but by some trick we can update the InMemory object. i am going to explain the way by using simple Console Application.
you can download this example application here.

Step:1 Create new Console Application.

Step:2 Create one Sample Class for testing.for me its Person.vb that contains below properties.

    Public Property ID As Integer
    Public Property Name As String
    Public Property Address As String
    


Step:3 now just Copy this code in default Module1.vb of Console Application. i will explain it later.


     Sub Main()
        Dim obj As New List(Of Person)
        obj.Add(New Person With {.ID = 1, .Name = "pravin", .Address = "Madhapar"})
        obj.Add(New Person With {.ID = 2, .Name = "prabhat", .Address = "Madhapar"})
        obj.Add(New Person With {.ID = 3, .Name = "anil", .Address = "Madhapar"})


        obj.ForEach(Function(x) updateObj(x, AddressOf updateObj_Two))
        'comment out this for next function test
        'obj.ForEach(Function(x) updateObj_Two(x))


        PrintObject(obj)

        Console.ReadKey()
    End Sub


    Function updateObj(ByRef obj As Person, ByVal ac As MyAction(Of Person)) As Boolean

        Return ac(obj)



    End Function

    Public Delegate Function MyAction(Of person)(ByRef p As Person)

    Function updateObj_Two(ByRef obj As Person) As Boolean
        'remember you have to copy individual property otherwise it doesn't work

        obj.Name = obj.Name & "-" & "Updated"
        obj.Address = obj.Address & "-" & "Updated"

        'this one for response to linq
        Return True

    End Function



    Sub PrintObject(ByVal obj As List(Of Person))
        For Each i In obj
            Console.WriteLine("Name:" & i.Name & " Address:" & i.Address)

        Next

    End Sub
    

In this example I create three functions updateObj for first method of updating object.updateObj_Two for second method of updating object.PrintObject for just print objects values.

you have Copy or Update individual property or you can use Reflection to copy the property of Object. = operator for copying object doesn't work.

  • updateObj function accept the object using ByRef so it direct effect changes to original object.
  • updateObj_Two function accept object as ByVal and second argument as function to call for updating Object,for that we create one Delegate MyAction that accept Passed Object as ByRef and create Parameter type from that delegate.
  • PrintObject for just printing the object's values.

and finally in Main function of Module1.vb we create one List of Person Class Object and using Linq function to operate our Update function on each Object of list.