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
}
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.
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.
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).
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() .
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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With