You can do it with reflection:
// Obtain a list of properties of string type
var stringProps = OS_Result
.OSResultStruct
.GetType()
.GetProperties()
.Where(p => p.PropertyType == typeof(string));
foreach (var prop in stringProps) {
// Use the PropertyInfo object to extract the corresponding value
// from the OS_Result.OSResultStruct object
string val = (string)prop.GetValue(OS_Result.OSResultStruct);
...
}
[EDIT by Matthew Watson]
I've taken the liberty of adding a further code sample, based on the code above.
You could generalise the solution by writing a method that will return an IEnumerable<string>
for any object type:
public static IEnumerable<KeyValuePair<string,string>> StringProperties(object obj)
{
return from p in obj.GetType().GetProperties()
where p.PropertyType == typeof(string)
select new KeyValuePair<string,string>(p.Name, (string)p.GetValue(obj));
}
And you can generalise it even further with generics:
public static IEnumerable<KeyValuePair<string,T>> PropertiesOfType<T>(object obj)
{
return from p in obj.GetType().GetProperties()
where p.PropertyType == typeof(T)
select new KeyValuePair<string,T>(p.Name, (T)p.GetValue(obj));
}
Using this second form, to iterate over all the string properties of an object you could do:
foreach (var property in PropertiesOfType<string>(myObject)) {
var name = property.Key;
var val = property.Value;
...
}