5

I have found that this question is quite common, but i didn't found what i am looking for. Maybe 'cause i want to do something else.

So i am currently coding for a webcrawler and need to compare objects in a list. What i want to do ist loop through the list, find duplicates, and when i found duplicates merge these.

When merging i want to:
- keep the information of the latest/most up to date object.
- if a field of the latest object is empty, take the value of the old objects field

I thought looping through the properties of the two objects would be the easiest.

I've tried a lot of things using reflection, all i could achieve was to show the property names of a class. What i want though is their values.

If possible, i would use a loop like this:

foreach(property prop in myObject)
{
    string value = myObject.prop;
    //do something
}

Is that possible? Or am i missing something?

Soner Gönül
  • 97,193
  • 102
  • 206
  • 364
David
  • 101
  • 1
  • 1
  • 8
  • *need to compare objects in a list* What objects? Do you control them? – Yuval Itzchakov May 27 '15 at 07:29
  • 1
    Can't you make use of IComparable interface? Do you really need to make use of reflection? – danish May 27 '15 at 07:30
  • Do you know what the objects are beforehand, or are they dynamic in nature? – Captain Kenpachi May 27 '15 at 07:35
  • The way you are comparing and merging those objects tells me that they are quite similar. Why not use an interface or common super class to abstract the properties you want to compare/merge? Using reflection for this sounds like a very bad idea. – Good Night Nerd Pride May 27 '15 at 07:42
  • Yes i control them. They are the same objects, of a class i created. I neither know how to use IComparable nor how to make use of a super class. Could you please explain? – David May 30 '15 at 12:47

2 Answers2

15

Something like:

object obj = new object();
PropertyInfo[] properties = obj.GetType().GetProperties();
foreach (var p in properties)
{
    var myVal = p.GetValue(obj);
}   

Note you need to allocate the object and pass it into the PropertyInfo.

Ospho
  • 2,756
  • 5
  • 26
  • 39
0

In order to work with foreach loop, you need to work with <dictionary> which is exactly what you need here. Store your class inside <dictionary> list give it T key and T value and loop through the class. This way it will be easier for you the keep track of your class and maintain those filters you want.

Barr J
  • 10,636
  • 1
  • 28
  • 46