c#的datatable轉(zhuǎn)list示例
using System;
using System.Collections.Generic;
using System.Data;
using System.Reflection;
namespace jdrz.HumanIdentify
{
public class Helper
{
/// <summary>
/// DataTable 轉(zhuǎn)換為List 集合
/// </summary>
/// <typeparam name="TResult">類型</typeparam>
/// <param name="dt">DataTable</param>
/// <returns></returns>
public static List<TResult> ToList<TResult>(DataTable dt) where TResult : class, new()
{
//創(chuàng)建一個屬性的列表
var prlist = new List<PropertyInfo>();
//獲取TResult的類型實例 反射的入口
var t = typeof(TResult);
//獲得TResult 的所有的Public 屬性 并找出TResult屬性和DataTable的列名稱相同的屬性(PropertyInfo) 并加入到屬性列表
Array.ForEach(t.GetProperties(), p => { if (dt.Columns.IndexOf(p.Name) != -1) prlist.Add(p); });
//創(chuàng)建返回的集合
var oblist = new List<TResult>();
foreach (DataRow row in dt.Rows)
{
//創(chuàng)建TResult的實例
var ob = new TResult();
//找到對應(yīng)的數(shù)據(jù) 并賦值
prlist.ForEach(p => { if (row[p.Name] != DBNull.Value) p.SetValue(ob, row[p.Name], null); });
//放入到返回的集合中.
oblist.Add(ob);
}
return oblist;
}
}
}
- C#中泛型舉例List<T>與DataTable相互轉(zhuǎn)換
- c#中DataTable轉(zhuǎn)List的2種方法示例
- C#中將DataTable轉(zhuǎn)化成List<T>的方法解析
- C#實現(xiàn)DataTable,List和Json轉(zhuǎn)換的方法
- C#實現(xiàn)DataTable轉(zhuǎn)換成IList的方法
- C#將DataTable轉(zhuǎn)化為List<T>
- C#將DataTable轉(zhuǎn)換成list的方法
- c#將list類型轉(zhuǎn)換成DataTable方法示例
- C#中DataTable和List互轉(zhuǎn)的示例代碼
相關(guān)文章
C#實現(xiàn)圖表中鼠標(biāo)移動并顯示數(shù)據(jù)
這篇文章主要為大家詳細(xì)介紹了C#實現(xiàn)圖表中鼠標(biāo)移動并顯示數(shù)據(jù),文中示例代碼介紹的非常詳細(xì),具有一定的參考價值,感興趣的小伙伴們可以參考一下2022-02-02深入C#中使用SqlDbType.Xml類型參數(shù)的使用詳解
本篇文章是對在C#中使用SqlDbType.Xml類型參數(shù)的使用進(jìn)行了詳細(xì)的分析介紹,需要的朋友參考下2013-05-05