Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Ok, let's have some fun:</p> <pre><code>public static class DataTableExtensions { public static List&lt;T&gt; ToGenericList&lt;T&gt;(this DataTable datatable, Func&lt;DataRow, T&gt; converter) { return (from row in datatable.AsEnumerable() select converter(row)).ToList(); } } class EDog { private int intIdDog; private int intIdOwner; private int intAge; private string strName; ... public static EDog Converter(DataRow row) { return new EDog { intIdDog = (int)row["IdDog"], intIdOwner = (int)row["IdOwner"], intAge = (int)row["Age"], strName = row["Name"] as string }; } } </code></pre> <p>Usage:</p> <pre><code>List&lt;EDog&gt; dogs = dsDogs.Tables[0].ToGenericList&lt;EDog&gt;(EDog.Converter); </code></pre> <p>But there is not enough fun, right? What about this:</p> <pre><code>class DataRowKeyAttribute : Attribute { private readonly string _Key; public string Key { get { return _Key; } } public DataRowKeyAttribute(string key) { _Key = key; } } static class DataTableExtensions { public static List&lt;T&gt; ToGenericList&lt;T&gt;(this DataTable datatable) where T : new() { return (from row in datatable.AsEnumerable() select Convert&lt;T&gt;(row)).ToList(); } private static T Convert&lt;T&gt;(DataRow row) where T : new() { var result = new T(); var type = result.GetType(); foreach (var fieldInfo in type.GetFields(BindingFlags.NonPublic | BindingFlags.Instance)) { var dataRowKeyAttribute = fieldInfo.GetCustomAttributes(typeof (DataRowKeyAttribute), true).FirstOrDefault() as DataRowKeyAttribute; if (dataRowKeyAttribute != null) { fieldInfo.SetValue(result, row[dataRowKeyAttribute.Key]); } } return result; } } class EDog { [DataRowKey("IdDog")] private int intIdDog; [DataRowKey("IdOwner")] private int intIdOwner; [DataRowKey("Age")] private int intAge; [DataRowKey("Name")] private string strName; ... } </code></pre> <p>Usage:</p> <pre><code>List&lt;EDog&gt; dogs = dsDogs.Tables[0].ToGenericList&lt;EDog&gt;(); </code></pre> <p>And if you want to have REAL fun, add error handling, consider caching reflection data to improve performance and changing fields to properties.</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
    1. This table or related slice is empty.
 

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