How can I access dynamically properties from a generated LINQ class ?
Cause I would like to be able to customize the displayed table columns where Partner is the LINQ Class generated from a SQL Server Database Table.
<table class="grid">
<thead>
<tr>
<% foreach (Column c in (IEnumerable)ViewData["columns"]) { %>
<th><%= c.Title %></th>
<% } %>
</tr>
</thead>
<tbody>
<% foreach (Partner p in (IEnumerable)ViewData.Model) { %>
<tr>
<% foreach (Column c in (IEnumerable)ViewData["columns"]) { %>
????? <th> <%= p.GetProperty(c.Name) %> </th> ?????
<% } %>
</tr>
<% } %>
</tbody>
</table>
Any idea how the code of the p.GetProperty(c.Name) method could look like ?
Forgive me if the Question is very simple but as I'm new to C# and LINQ I really couldn't figure it out.
Reflection should provide what you want - in particular,
typeof(Partner).GetProperty(c.Name).GetValue(p, null)
However, you might want to do this before the loop:
var columns = (IEnumerable<string>)ViewData["columns"];
var cols = columns.Select(colName =>
typeof(Partner).GetProperty(colName)).ToList();
This gives you a set of re-usable PropertyInfo instances that you can use per row:
foreach (var col in cols) { %>
<th><%= col.GetValue(p,null) %></th>
<% }
(should that <th/> be a <td/>, by the way?)
That should be a bit more efficient than repeatedly finding each property. There are other ways of doing this too (faster again).
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