Dynamically compare 2 entity property values in VB.net

Had a scenario today where we had to compare the property values of view model against a domain entity, so I wrote simple windows client sample to dynamically compare properties with the same name to dynamically compare values and if the values are different just add the names of these properties to a list

On Load I create 2 entities _person and _student; person has name and age properties; _student has name, age, sex and school. On comparing _person and _student we find “name” property values differ, age is same, sex and school does not apply to person class. So the only property I want in difference list is “name”

Code Snippet
  1. Public Class Form1
  2.     Private _person As Person
  3.     Private _student As Student
  4.     Private Sub Compare_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Compare.Click
  5.         Dim diffList As New List(Of String)
  6.         For Each personProp In _person.GetType.GetProperties
  7.             Dim studentValue = _student.GetType.GetProperty(personProp.Name).GetValue(_student, Nothing)
  8.             Dim personValue = _person.GetType.GetProperty(personProp.Name).GetValue(_person, Nothing)
  9.             If studentValue <> personValue Then
  10.                 diffList.Add(personProp.Name)
  11.             End If
  12.         Next
  13.     End Sub
  14.     Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
  15.         _person = New Person With {.name = “A”, .age = 10}
  16.         _student = New Student With {.name = “B”, .age = 10, .sex = “m”, .school = “XYZ”}
  17.     End Sub
  18. End Class
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s