List和DataTable相互轉換
一、List<T>/IEnumerable轉換到DataTable/DataView
方法一:
/// <summary>
/// Convert a List{T} to a DataTable.
/// </summary>
private DataTable ToDataTable<T>(List<T> items)
{
var tb = new DataTable(typeof (T).Name);
PropertyInfo[] props = typeof (T).GetProperties(BindingFlags.Public | BindingFlags.Instance);
foreach (PropertyInfo prop in props)
{
Type t = GetCoreType(prop.PropertyType);
tb.Columns.Add(prop.Name, t);
}
foreach (T item in items)
{
var values = new object[props.Length];
for (int i = 0; i < props.Length; i++)
{
values[i] = props[i].GetValue(item, null );
}
tb.Rows.Add(values);
}
return tb;
}
/// <summary>
/// Determine of specified type is nullable
/// </summary>
public static bool IsNullable(Type t)
{
return !t.IsValueType || (t.IsGenericType && t.GetGenericTypeDefinition() == typeof(Nullable<>));
}
/// <summary>
/// Return underlying type if type is Nullable otherwise return the type
/// </summary>
public static Type GetCoreType(Type t)
{
if (t != null && IsNullable(t))
{
if (!t.IsValueType)
{
return t;
}
else
{
return Nullable.GetUnderlyingType(t);
}
}
else
{
return t;
}
}
方法二:
public static DataTable ToDataTable<T>(IEnumerable<T> collection)
{
var props = typeof(T).GetProperties();
var dt = new DataTable();
dt.Columns.AddRange(props.Select(p => new DataColumn(p.Name, p.PropertyType)).ToArray());
if (collection.Count() > 0)
{
for (int i = 0; i < collection.Count(); i++)
{
ArrayList tempList = new ArrayList();
foreach (PropertyInfo pi in props)
{
object obj = pi.GetValue(collection.ElementAt(i), null);
tempList.Add(obj);
}
object[] array = tempList.ToArray();
dt.LoadDataRow(array, true);
}
}
return dt;
}
二、DataTable轉換到List
方法一:
public static IList<T> ConvertTo<T>(DataTable table)
{
if (table == null)
{
return null;
}
List<DataRow> rows = new List<DataRow>();
foreach (DataRow row in table.Rows)
{
rows.Add(row);
}
return ConvertTo<T>(rows);
}
public static IList<T> ConvertTo<T>(IList<DataRow> rows)
{
IList<T> list = null;
if (rows != null)
{
list = new List<T>();
foreach (DataRow row in rows)
{
T item = CreateItem<T>(row);
list.Add(item);
}
}
return list;
}
public static T CreateItem<T>(DataRow row)
{
T obj = default(T);
if (row != null)
{
obj = Activator.CreateInstance<T>();
foreach (DataColumn column in row.Table.Columns)
{
PropertyInfo prop = obj.GetType().GetProperty(column.ColumnName);
try
{
object value = row[column.ColumnName];
prop.SetValue(obj, value, null);
}
catch
{ //You can log something here
//throw;
}
}
}
return obj;
}
方法二:
把查詢結果以DataTable返回很方便,但是在檢索資料時又很麻煩,沒有模型型別檢索方便。
所以很多人都是按照以下方式做的:
// 獲得查詢結果
DataTable dt = DbHelper.ExecuteDataTable(...);
// 把DataTable轉換為IList<UserInfo>
IList<UserInfo> users = ConvertToUserInfo(dt);
問題:如果此係統有幾十上百個模型,那不是每個模型中都要寫個把DataTable轉換為此模型的方法嗎?
解決:能不能寫個通用類,可以把DataTable轉換為任何模型,呵呵,這就需要利用反射和泛型了
using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using System.Reflection;
namespace NCL.Data
{
/// <summary>
/// 實體轉換輔助類
/// </summary>
public class ModelConvertHelper<T> where T : new()
{
public static IList<T> ConvertToModel(DataTable dt)
{
// 定義集合
IList<T> ts = new List<T>();
// 獲得此模型的型別
Type type = typeof(T);
string tempName = "";
foreach (DataRow dr in dt.Rows)
{
T t = new T();
// 獲得此模型的公共屬性
PropertyInfo[] propertys = t.GetType().GetProperties();
foreach (PropertyInfo pi in propertys)
{
tempName = pi.Name; // 檢查DataTable是否包含此列
if (dt.Columns.Contains(tempName))
{
// 判斷此屬性是否有Setter
if (!pi.CanWrite) continue;
object value = dr[tempName];
if (value != DBNull.Value)
pi.SetValue(t, value, null);
}
}
ts.Add(t);
}
return ts;
}
}
}
使用方式:
// 獲得查詢結果
DataTable dt = DbHelper.ExecuteDataTable(...);
// 把DataTable轉換為IList<UserInfo>
IList<UserInfo> users = ModelConvertHelper<UserInfo>.ConvertToModel(dt);
相關推薦
List和DataTable相互轉換
一、List<T>/IEnumerable轉換到DataTable/DataView 方法一: /// <summary> /// Convert a List{T} to a DataTable. /// </summar
封裝一個List集合和datatable相互轉換的工具類
oda info data 反射 arr key 建表 contain 信息 /// <summary> /// List轉換為DataTable對象 /// </summary> public class List
java中List和Array相互轉換
一個 data element 分隔 -a common 內部類 iter lang List to Array List 提供了toArray的接口,所以可以直接調用轉為object型數組 List<String> list = new ArrayLis
C#.net開發 List與DataTable相互轉換
inf columns serve property eat 這一 異常 bject 屬性 1、DataTable轉List集合 /// <summary> /// DataTable轉化為List集合 ///
list和string相互轉換
一、list轉string StringUtils.join()和String.join():可用來把字串陣列拼接成整條字串,效果一樣只是用法稍有不同,StringUtils要引入jar包common-lang3, String.join()是JDK8新增方法。 例子如下:
集合框架(一)續 向集合中新增一個集合、陣列和List之間的相互轉換、從集合中刪除另一個集合所包含的元素
集合方法集結: import java.util.ArrayList; import java.util.Arrays; import java.util.HashSet; import java.util.LinkedList; import java.util.List
list和datatable的相互轉化
list轉datatble public static DataTable ListToDataTable(IList list) { //返回物件result 例項化 DataTable result =
NSDate和NSString相互轉換
date 部分 當前 sda 英文 none 剛剛在線 轉換 微信公眾號 不積小流無以成江海,不及矽步無以至千裏。做iOS開發也是這樣。平時寫代碼要多收集一些實用的代碼,以免每次都從新來一遍,不僅浪費時間,也影響開發效率。 有人把做app形容成蓋房子。碼農
Android中 Bitmap和Drawable相互轉換的方法
canvas board null height .com factory oar tool pla 1、Drawable --> Bitmap [java] view plain copy Bitmap drawable2Bitmap(Drawabl
數據集和JSON相互轉換
tostring 解析 con orm sys tail while string XML 使用DELPHI原生類實現數據集和JSON相互轉換 JSON二要素:數組和對象。對象可以包含數組,數組可以包含對象。無層數限制。OLEVARIANT也類似,OLEVARIANT的一
PHP時間戳和日期相互轉換(文字有問題)
它的 內容 log dex 不同 cnblogs ont cti time() 在php中我們要把時間戳轉換日期可以直接使用date函數來實現,如果要把日期轉換成時間戳可以使用strtotime()函數實現,下面我來給大家舉例說明。 1.php中時間轉換函
java JSON 和 Object 相互轉換
eva sta art XML null jackson log () struct 1、導入 jackson jar <dependency> <groupId>com.fasterxml.jackson.core</groupId
基本數據類型和String相互轉換
相互 color 結果 val ring pre integer args static 1 package com.jdk7.chapter5; 2 3 public class BasicToString { 4 /** 5 * 基本數據
PHP數組和XML相互轉換的函數
ret val ble lib key decode 轉換 相互 simplexml //數組轉xml function ArrtoXml($arr) { if(!is_array($arr) || count($arr) == 0) ret
Python 時間戳和日期相互轉換
sds 工作 num 一定的 方便 number http times time 轉載地址:http://liyangliang.me/posts/2012/10/python-timestamp-to-timestr/ 在寫Python的時候經常會遇到時間格式的問
int和String相互轉換
public class Demo3_Integer { /** * * A:int -- String * a:和""進行拼接 * b:public static String valueOf(int i) * c:int -- Integer -- String
c語言入門將ASCII碼和字元相互轉換及其思考
#include<stdio.h> void main() { unsigned char a; printf("enter char:"); scanf("%C",& a ); printf("ascii = %d", a );//強制轉化為ascii碼 } 同理;
LUA LUA中table和字串相互轉換
LUA中table和字串相互轉換 有時會遇到需要將一個table儲存起來或傳遞給另一個string中的時候,table的序列化和反序列化就起到作用了。 需要使用到一個輔助函式 function ToSt
python2中將Unicode編碼的中文和str相互轉換
在python2x版本中 關於中文漢字轉換 1.中文------字串格式 >>> s = '漢字' >>> type(s) <type 'str'> 預設漢字型別是:str 列印 s 時會顯示如下內容:反斜槓和字母組合,一個漢字對應兩組這樣的組
Json與List之間的相互轉換
谷歌的Gson.jar: //list轉換為json Gson gson = new Gson(); List<Person> persons = new ArrayList<Person>(); String str = gson.toJson(persons)