vendredi 30 novembre 2018

How to iterate two non-trivial class object's properties at the same time in C# similar to Python's zip method

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
}





Aucun commentaire:

Enregistrer un commentaire