02/10/2018, 00:06
[C#] Function convert DataTable to List và ngược lại trong lập trình csharp
Hôm nay, mình xin share 2 function convert qua lại giữa datatable và list trong lập trình c# . Trong lập trình csharp , tùy trường hợp ta cần sử dụng List hoặc datatable để xử lý. Thì với 2 hàm bên dưới sẽ giúp cho các bạn dễ dàng chuyển đổi. ...
Hôm nay, mình xin share 2 function convert qua lại giữa datatable và list trong lập trình c#.
Trong lập trình csharp, tùy trường hợp ta cần sử dụng List hoặc datatable để xử lý. Thì với 2 hàm bên dưới sẽ giúp cho các bạn dễ dàng chuyển đổi.

1. Function chuyển đổi List to Datatable C#
public static DataTable ListToDataTable(this IList data)
{
DataTable dataTable = new DataTable(typeof(T).Name);
PropertyInfo[] props = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance);
foreach (PropertyInfo prop in props)
{
dataTable.Columns.Add(prop.Name, Nullable.GetUnderlyingType(prop.PropertyType) ?? prop.PropertyType);
}
foreach (T item in data)
{
var values = new object[props.Length];
for (int i = 0; i < props.Length; i++)
{
values[i] = props[i].GetValue(item, null);
}
dataTable.Rows.Add(values);
}
return dataTable;
}
2. Function chuyển đổi từ Datatable to List C#
public static List DataTableToList(this DataTable table) where T : class, new()
{
try
{
List list = new List();
foreach (var row in table.AsEnumerable())
{
T obj = new T();
foreach (var prop in obj.GetType().GetProperties())
{
try
{
PropertyInfo propertyInfo = obj.GetType().GetProperty(prop.Name);
propertyInfo.SetValue(obj, Convert.ChangeType(row[prop.Name], propertyInfo.PropertyType), null);
}
catch
{
continue;
}
}
list.Add(obj);
}
return list;
}
catch
{
return null;
}
}
CHÚC CÁC BẠN THÀNH CÔNG!