Last active
February 2, 2021 19:09
-
-
Save jknopp/97d6cc659439f591748df32cbd642fa6 to your computer and use it in GitHub Desktop.
Helpful DataRow/DataTable Extensions
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public static class DataTableExtensions | |
{ | |
public static List<T> ToList<T>(this DataTable table) where T : new() | |
{ | |
IList<PropertyInfo> properties = typeof(T).GetProperties().ToList(); | |
List<T> result = new List<T>(); | |
foreach (var row in table.Rows) | |
{ | |
var item = CreateItemFromRow<T>((DataRow)row, properties); | |
result.Add(item); | |
} | |
return result; | |
} | |
// Consider moving to DataRowExtensions class | |
private static T CreateItemFromRow<T>(DataRow row, IEnumerable<PropertyInfo> properties) where T : new() | |
{ | |
if (properties == null) throw new ArgumentNullException(nameof(properties)); | |
T item = new T(); | |
foreach (var property in properties) | |
{ | |
if (row.Table.Columns.Contains(property.Name)) | |
{ | |
if (property.PropertyType == typeof(DayOfWeek)) | |
{ | |
DayOfWeek day = (DayOfWeek)Enum.Parse(typeof(DayOfWeek), row[property.Name].ToString()); | |
property.SetValue(item, day, null); | |
} | |
else | |
{ | |
property.SetValue(item, row[property.Name] == DBNull.Value ? null : row[property.Name], null); | |
} | |
} | |
} | |
return item; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment