tags:

views:

66

answers:

4

I have List (Of Report). Report has 90 properties. I dont want write them each and every propertiy to get values for properties. Is there any waht to get propeties values from the List

Ex:

Dim mReports as new List(Of Reports)
mReport = GetReports()

For each mReport as Report In mReports
   'Here I want get all properties values without writing property names
next
+6  A: 

You can use reflection:

static readonly PropertyInfo[] properties = typeof(Reports).GetProperties();

foreach(var property in properties) {
    property.GetValue(someInstance);
}

However, it will be slow.

In general, a class with 90 proeprties is poor design.
Consider using a Dictionary or rethinking your design.

SLaks
A: 
PropertyInfo[] props = 
     obj.GetType().GetProperties(BindingFlags.Public |BindingFlags.Static);
foreach (PropertyInfo p in props)
{
  Console.WriteLine(p.Name);
}
stackunderflow
+1  A: 

I don't speak VB.NET fluently, but you can easily translate something like this to VB.NET.

var properties = typeof(Report).GetProperties();
foreach(var mReport in mReports) {
    foreach(var property in properties) {
       object value = property.GetValue(mReport, null);
       Console.WriteLine(value.ToString());
    }
}

This is called reflection. You can read about its uses in .NET on MSDN. I used Type.GetProperties to get the list of properties, and PropertyInfo.GetValue to read the values. You might need to add various BindingFlags or check properties like PropertyInfo.CanRead to get exactly the properties that you want. Additionally, if you have any indexed properties, you will have to adjust the second parameter to GetValue accordingly.

Jason
+1  A: 

Sounds like a good fit for reflection or meta-programming (depending on the performance required).

var props=typeof(Report).GetProperties();
foreach(var row in list)
foreach(var prop in props)
    Console.WriteLine("{0}={1}",
        prop.Name,
        prop.GetValue(row));
Marc Gravell