1

How do I iterate two non-trivial class objects at the same time to check their properties?

These post1 post2 talks about how to do it with generic default data structures, but what if it is a custom class and I cannot modify it, say, something like

public class A
{
   public int propA { get; set; }
   public int propB { get; set; }
   ...
}

Also it does not have a GetEnumerator() method. How do I do something similar to Python's zip while using reflection? So I can do something like:

foreach(var pair in zip(myClassObj1.GetType().GetProperties(), myClasObj2.GetType().GetProperties())
{
   var name1 = pair.Item1.Name;
   var name2 = pair.Item2.Name;

   var value1 = pair.Item1.GetValue(myClassObj1, null);
   var value2 = pair.Item2.GetValue(myClassObj2, null);

   // do things
}
cli2
  • 239
  • 1
  • 5
  • 12

2 Answers2

1

You need to use reflection for that (System.Reflection). First of all, you need to get the Type object of the object of the object you want to get all the properties from. Then, call the method GetProperties(), which will return an array of PropertyInfo objects. Then run all over that objects collecting the info you need.

public static IDictionary<string, object> GetAllProperties(object obj)
{
    var toret = new Dictionary<string, object>();
    Type objType = obj.GetType();
    PropertyInfo[] properties = objType.GetProperties();

    foreach(PropertyInfo pinfo in properties) {
        toret.Add( pinfo.Name, pinfo.GetValue( obj ) );
    }

    return toret;
}

For example, for an object like this one:

class Foo {
    public int A { get; set; }
    public int B { get; set; }
}

You can show the properties names and values of a given object by:

class Ppal {
    public static void Main()    
    {
            var foo = new Foo{ A = 5, B = 6 };

            foreach(KeyValuePair<string, object> pair in GetAllProperties( foo ) ) {
                Console.WriteLine( "Foo.{0} = {1}", pair.Key, pair.Value );
            }
    }
}

Hope this helps.

Baltasarq
  • 12,014
  • 3
  • 38
  • 57
0

This post gave me the tools needed to for enumerating the properties of the two classes in one foreach loop

foreach(var prop in obj1.GetType().GetProperites().Zip(obj2.GetType().GetProperties(), (a,b) => Tuple.Create(a,b))
{
    var name1 = prop.Item1.Name;
    var name2 = prop.Item2.Name;

    var value1 = prop.Item1.GetValue(obj1, null);
    var value2 = prop.Item2.GetValue(obj2, null);

    // do things
}
cli2
  • 239
  • 1
  • 5
  • 12