I am trying to create a SortedList
of property names and values for any object. The two methods below iterate an object's properties storing its respective values in a sorted list (if there is a better mechanism for accomplishing this please recommend it).
With my current implementation I am running into issues with Index Properties. Object.GetType Method provides a mechanism to specify an array of index properties but I am unsure how to utilize it to get all of the values for the property. For the time being I'd like to concatenate all of the values into a delimited single string.
private static SortedList<string, string> IterateObjProperties(object obj)
{
IDictionaryEnumerator propEnumerator = ObjPropertyEnumerator(obj);
SortedList<string, string> properties = new SortedList<string, string>();
while (propEnumerator.MoveNext())
{
properties.Add(propEnumerator.Key.ToString(),
propEnumerator.Value is String
? propEnumerator.Value.ToString() : String.Empty);
}
return properties;
}
private static IDictionaryEnumerator ObjPropertyEnumerator(object obj)
{
Hashtable propertiesOfObj = new Hashtable();
Type t = obj.GetType();
PropertyInfo[] pis = t.GetProperties();
foreach (PropertyInfo pi in pis)
{
if (pi.GetIndexParameters().Length == 0)
{
propertiesOfObj.Add(pi.Name,
pi.GetValue(obj, Type.EmptyTypes).ToString());
}
else
{
// do something cool to store an index property
// into a delimited string
}
}
return propertiesOfObj.GetEnumerator();
}