Last active
April 23, 2017 12:56
-
-
Save bezzad/7ebf3fea6628186e024f4e59029c4695 to your computer and use it in GitHub Desktop.
Extension methods for convert `DataTable` to any other types like: Generic Type `T` , dynamic object
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 Extension | |
{ | |
public static IList<T> ToList<T>(this DataTable dt, bool isFirstRowColumnsHeader = false) where T : new() | |
{ | |
var results = new List<T>(); | |
if (dt != null && dt.Rows.Count > 0) | |
{ | |
var columns = dt.Columns.Cast<DataColumn>().ToList(); | |
var rows = dt.Rows.Cast<DataRow>().ToList(); | |
var headerNames = columns.Select(col => col.ColumnName).ToList(); | |
// | |
#region Find properties name or columns name | |
if (isFirstRowColumnsHeader) | |
{ | |
for (var i = 0; i < headerNames.Count; i++) | |
{ | |
if (rows[0][i] != DBNull.Value && !string.IsNullOrEmpty(rows[0][i].ToString())) | |
headerNames[i] = rows[0][i].ToString(); | |
} | |
// | |
// remove first row because that is header | |
rows.RemoveAt(0); | |
} | |
#endregion | |
// | |
#region Create dynamic or anonymous object for `T type | |
if (typeof(T) == typeof(ExpandoObject) || | |
typeof(T) == typeof(DynamicObject) || | |
typeof(T) == typeof(object)) | |
{ | |
var dynamicDt = new List<dynamic>(); | |
foreach (var row in rows) | |
{ | |
dynamic dyn = new ExpandoObject(); | |
dynamicDt.Add(dyn); | |
for (var i = 0; i < columns.Count; i++) | |
{ | |
var dic = (IDictionary<string, object>)dyn; | |
dic[headerNames[i]] = row[columns[i]]; | |
} | |
} | |
return (dynamic)dynamicDt; | |
} | |
#endregion | |
#region T is User Defined Types | |
else // other types of `T | |
{ | |
var properties = typeof(T).GetProperties(); | |
if (columns.Any() && properties.Any()) | |
{ | |
foreach (var row in rows) | |
{ | |
var entity = new T(); | |
for (var i = 0; i < columns.Count; i++) | |
{ | |
if (!row.IsNull(columns[i])) | |
{ | |
// Find the property by json property attribute name whiche is equal by this header name | |
var property = | |
properties.FirstOrDefault( | |
prop => ((DisplayNameAttribute)prop.GetCustomAttribute(typeof(DisplayNameAttribute), true))?.DisplayName == headerNames[i] || | |
prop.Name == headerNames[i]); | |
// | |
property? // ? -> maybe the property by name `headerNames[i]` is not exist in entity then get null! | |
.SetValue(entity, row[columns[i]] == DBNull.Value ? null : Convert.ChangeType(row[columns[i]], property.PropertyType)); | |
} | |
} | |
results.Add(entity); | |
} | |
} | |
} | |
#endregion | |
} | |
return results; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment