I have a class containing several properties (all are strings if it makes any difference).
I also have a list, which contains many different instances of the class.
A copy-paste solution (extension methods) mostly based on earlier responses to this question.
Also properly handles IDicitonary (ExpandoObject/dynamic) which is often needed when dealing with this reflected stuff.
Not recommended for use in tight loops and other hot paths. In those cases you're gonna need some caching/IL emit/expression tree compilation.
public static IEnumerable<(string Name, object Value)> GetProperties(this object src)
{
if (src is IDictionary dictionary)
{
return dictionary.Select(x => (x.Key, x.Value));
}
return src.GetObjectProperties().Select(x => (x.Name, x.GetValue(src)));
}
public static IEnumerable GetObjectProperties(this object src)
{
return src.GetType()
.GetProperties(BindingFlags.Public | BindingFlags.Instance)
.Where(p => !p.GetGetMethod().GetParameters().Any());
}