Example of datatable to list for c
- 2020-06-15 10:07:07
- OfStack
using System;
using System.Collections.Generic;
using System.Data;
using System.Reflection;
namespace jdrz.HumanIdentify
{
public class Helper
{
/// <summary>
/// DataTable convert List A collection of
/// </summary>
/// <typeparam name="TResult"> type </typeparam>
/// <param name="dt">DataTable</param>
/// <returns></returns>
public static List<TResult> ToList<TResult>(DataTable dt) where TResult : class, new()
{
// create 1 A list of attributes
var prlist = new List<PropertyInfo>();
// To obtain TResult Type instance of Reflected entrance
var t = typeof(TResult);
// To obtain TResult Of all the Public attribute And find out TResult Properties and DataTable Attributes with the same column name (PropertyInfo) And add it to the property list
Array.ForEach(t.GetProperties(), p => { if (dt.Columns.IndexOf(p.Name) != -1) prlist.Add(p); });
// Creates the returned collection
var oblist = new List<TResult>();
foreach (DataRow row in dt.Rows)
{
// create TResult An instance of the
var ob = new TResult();
// Find the corresponding data And the assignment
prlist.ForEach(p => { if (row[p.Name] != DBNull.Value) p.SetValue(ob, row[p.Name], null); });
// Into the returned collection .
oblist.Add(ob);
}
return oblist;
}
}
}