Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to loop through a C# Class object?

Tags:

c#

I have a C# class that I want to loop through the properties as a key/value pair but don't know how.

Here is what I would like to do:

Foreach (classobjectproperty prop in classobjectname)
{
    if (prop.name == "somename")
        //do something cool with prop.value
}
like image 212
SLoret Avatar asked Oct 24 '10 19:10

SLoret


People also ask

How do I loop through an array in C?

To iterate over Array using While Loop, start with index=0, and increment the index until the end of array, and during each iteration inside while loop, access the element using index.

Can you loop through a struct?

You can iterate through an array of structs but not the struct members. Learn about Classes. You have a struct with function as well as data members. You can add functions to structs too, but it's best to learn the whole shtick.

Does C have for each loop?

There is no foreach in C. You can use a for loop to loop through the data but the length needs to be know or the data needs to be terminated by a know value (eg. null).

How do you go through a vector in C++?

In C++ , vectors can be indexed with []operator , similar to arrays. To iterate through the vector, run a for loop from i = 0 to i = vec. size() .


1 Answers

Yup:

Type type = typeof(Form); // Or use Type.GetType, etc
foreach (PropertyInfo property in type.GetProperties())
{
    // Do stuff with property
}

This won't give them as key/value pairs, but you can get all kinds of information from a PropertyInfo.

Note that this will only give public properties. For non-public ones, you'd want to use the overload which takes a BindingFlags. If you really want just name/value pairs for instance properties of a particular instance, you could do something like:

var query = foo.GetType()
               .GetProperties(BindingFlags.Public |
                              BindingFlags.Instance)
               // Ignore indexers for simplicity
               .Where(prop => !prop.GetIndexParameters().Any())
               .Select(prop => new { Name = prop.Name,
                                     Value = prop.GetValue(foo, null) });

foreach (var pair in query)
{
    Console.WriteLine("{0} = {1}", pair.Name, pair.Value);
}
like image 94
Jon Skeet Avatar answered Sep 28 '22 16:09

Jon Skeet