Reputation: 11672
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
Upvotes: 1
Views: 242
Reputation: 888273
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.
Upvotes: 6
Reputation: 241789
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.
Upvotes: 1
Reputation: 1064234
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));
Upvotes: 1
Reputation: 554
PropertyInfo[] props =
obj.GetType().GetProperties(BindingFlags.Public |BindingFlags.Static);
foreach (PropertyInfo p in props)
{
Console.WriteLine(p.Name);
}
Upvotes: 1