Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

loop through object and get properties [duplicate]

Tags:

c#

object

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;
    //......

}
like image 571
user1438082 Avatar asked Mar 23 '13 11:03

user1438082


1 Answers

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;
    ...
}
like image 59
Sergey Kalinichenko Avatar answered Sep 28 '22 17:09

Sergey Kalinichenko