10

i have a method that returns a list of operating system properties. Id like to loop through the properties and do some processing on each one.All properties are strings

How do i loop through the object

C#

// test1 and test2 so you can see a simple example of the properties - although these are not part of the question
String test1 = OS_Result.OSResultStruct.OSBuild;
String test2 = OS_Result.OSResultStruct.OSMajor;

// here is what i would like to be able to do
foreach (string s in OS_Result.OSResultStruct)
{
    // get the string and do some work....
    string test = s;
    //......

}
user1438082
  • 2,740
  • 10
  • 48
  • 82

2 Answers2

14

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;
    ...
}
Community
  • 1
  • 1
Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
2

You can use Reflection to loop the GetProperties Resullt:

OS_Result.OSResultStruct.GetType().GetProperties()