Using LINQ and reflection to find matching properties of objects

As a side product of some experiments I wrote simple LINQ query that matches properties of two objects and returns these properties as list. The code I wrote is pretty simple and I packed it for you as method.

C#

public IList<PropertyInfo> GetMatchingProperties(object source, object target)

{

    if (source == null)

        throw new ArgumentNullException("source");

    if (target == null)

        throw new ArgumentNullException("target");

 

    var sourceType = source.GetType();

    var sourceProperties = sourceType.GetProperties();

    var targetType = target.GetType();

    var targetProperties = targetType.GetProperties();

 

    var properties = (from s in sourceProperties

                      from t in targetProperties

                      where s.Name == t.Name &&

                            s.PropertyType == t.PropertyType

                      select s).ToList();

    return properties;

}


VB.NET
Public Function GetMatchingProperties(ByVal source As Object,_
    ByVal target As Object) As IList(Of PropertyInfo)

    If source Is Nothing Then
        Throw New ArgumentNullException("source")
    End If
    If target Is Nothing Then
        Throw New ArgumentNullException("target")
    End If
    
    Dim sourceType = source.GetType()
    Dim sourceProperties = sourceType.GetProperties()
    Dim targetType = target.GetType()
    Dim targetProperties = targetType.GetProperties()
    
    Dim properties = (From s In sourceProperties _
        From t In targetProperties _
        Where s.Name = t.Name AndAlso s.PropertyType = t.PropertyType _
        Select s).ToList()
    Return properties
End Function

The method returns only those properties that match by name and type. If both objects have property called Sum and both of them have Sum in different type (let’s say float and decimal) then this property is not returned by this method. Of course, you can extend this method if you like and you can make it much more clever. Simple implementation given here worked for me very well.

kick it on DotNetKicks.com pimp it Progg it 顶 Shout it
Shout it!

8 Comments

Comments have been disabled for this content.