Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>That won't be an actual <em>leak</em>, but it could be stressing things unnecessarily...</p> <p>How many rows are you working over? Note that reflection is a pain, and that every call to things like <code>GetCustomAttributes</code> can return a new array (so you want to do that once, not once per-property-per-row).</p> <p>Personally, I'd pre-construct the work I intend to do... something like below.</p> <p>Note that if I was doing this lots, I'd either switch to <a href="http://www.codeproject.com/KB/cs/HyperPropertyDescriptor.aspx" rel="noreferrer">HyperDescriptor</a>, or if .NET 3.5 was an option, maybe a compiled Expression. Since <code>DataTable</code> isn't strongly typed, <code>HyperDescriptor</code> would be a logical next step (for performance) after the below...</p> <pre><code>sealed class Tuple&lt;T1, T2&gt; { public Tuple() {} public Tuple(T1 value1, T2 value2) {Value1 = value1; Value2 = value2;} public T1 Value1 {get;set;} public T2 Value2 {get;set;} } public static List&lt;T&gt; Convert&lt;T&gt;(DataTable table) where T : class, new() { List&lt;Tuple&lt;DataColumn, PropertyInfo&gt;&gt; map = new List&lt;Tuple&lt;DataColumn,PropertyInfo&gt;&gt;(); foreach(PropertyInfo pi in typeof(T).GetProperties()) { ColumnAttribute col = (ColumnAttribute) Attribute.GetCustomAttribute(pi, typeof(ColumnAttribute)); if(col == null) continue; if(table.Columns.Contains(col.FieldName)) { map.Add(new Tuple&lt;DataColumn,PropertyInfo&gt;( table.Columns[col.FieldName], pi)); } } List&lt;T&gt; list = new List&lt;T&gt;(table.Rows.Count); foreach(DataRow row in table.Rows) { if(row == null) { list.Add(null); continue; } T item = new T(); foreach(Tuple&lt;DataColumn,PropertyInfo&gt; pair in map) { object value = row[pair.Value1]; if(value is DBNull) value = null; pair.Value2.SetValue(item, value, null); } list.Add(item); } return list; } </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload