C# 中 DataTable转换成IList
在用C#作开发的时候经常要把DataTable转换成IList;操作DataTable比较麻烦,把DataTable转换成IList,以对象实体作为IList的元素,操作起来就非常方便。
注意:实体的属性必须和数据库中的字段必须一一对应,或者数据库字段名.ToLower().Contains(实体属性名.ToLower())
数据类型暂时至支持int、string、DateTime、float、double

using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Reflection; namespace TBToListTest
{
publicclass TBToList<T>where T : new()
{
///<summary>
/// 获取列名集合
///</summary>
private IList<string> GetColumnNames(DataColumnCollection dcc)
{
IList<string> list =new List<string>();
foreach (DataColumn dc in dcc)
{
list.Add(dc.ColumnName);
}
return list;
} ///<summary>
///属性名称和类型名的键值对集合
///</summary>
private Hashtable GetColumnType(DataColumnCollection dcc)
{
if (dcc ==null|| dcc.Count ==0)
{
returnnull;
}
IList<string> colNameList = GetColumnNames(dcc); Type t =typeof(T);
PropertyInfo[] properties = t.GetProperties();
Hashtable hashtable =new Hashtable();
int i =0;
foreach (PropertyInfo p in properties)
{
foreach (string col in colNameList)
{
if (col.ToLower().Contains(p.Name.ToLower()))
{
hashtable.Add(col, p.PropertyType.ToString() + i++);
}
}
} return hashtable;
} ///<summary>
/// DataTable转换成IList
///</summary>
///<param name="dt"></param>
///<returns></returns>
public IList<T> ToList(DataTable dt)
{
if (dt ==null|| dt.Rows.Count ==0)
{
returnnull;
} PropertyInfo[] properties =typeof(T).GetProperties();//获取实体类型的属性集合
Hashtable hh = GetColumnType(dt.Columns);//属性名称和类型名的键值对集合
IList<string> colNames = GetColumnNames(hh);//按照属性顺序的列名集合
List<T> list =new List<T>();
T model =default(T);
foreach (DataRow dr in dt.Rows)
{
model =new T();//创建实体
int i =0;
foreach (PropertyInfo p in properties)
{
if (p.PropertyType ==typeof(string))
{
p.SetValue(model, dr[colNames[i++]], null);
}
elseif (p.PropertyType ==typeof(int))
{
p.SetValue(model, int.Parse(dr[colNames[i++]].ToString()), null);
}
elseif (p.PropertyType ==typeof(DateTime))
{
p.SetValue(model, DateTime.Parse(dr[colNames[i++]].ToString()), null);
}
elseif (p.PropertyType ==typeof(float))
{
p.SetValue(model, float.Parse(dr[colNames[i++]].ToString()), null);
}
elseif (p.PropertyType ==typeof(double))
{
p.SetValue(model, double.Parse(dr[colNames[i++]].ToString()), null);
}
} list.Add(model);
} return list;
} ///<summary>
/// 按照属性顺序的列名集合
///</summary>
private IList<string> GetColumnNames(Hashtable hh)
{
PropertyInfo[] properties =typeof(T).GetProperties();//获取实体类型的属性集合
IList<string> ilist =new List<string>();
int i =0;
foreach (PropertyInfo p in properties)
{
ilist.Add(GetKey(p.PropertyType.ToString() + i++, hh));
}
return ilist;
} ///<summary>
/// 根据Value查找Key
///</summary>
privatestring GetKey(string val, Hashtable tb)
{
foreach (DictionaryEntry de in tb)
{
if (de.Value.ToString() == val)
{
return de.Key.ToString();
}
}
returnnull;
} }
} namespace TBToListTest
{ //实体
publicclass Person
{
publicint ID
{
set;
get;
} publicstring Name
{
set;
get;
} publicstring Age
{
set;
get;
} publicstring Lover
{
set;
get;
} }
} using System;
using System.Data; namespace TBToListTest
{
class Program
{
staticvoid Main(string[] args)
{
TBToList<Person> tol =new TBToList<Person>();
Console.WriteLine();
DataTable dt = GetTable();
tol.ToList(dt);
Console.Read();
} publicstatic DataTable GetTable()
{
DataTable dt =new DataTable();
dt.Columns.Add("ID");
dt.Columns.Add("Age");
dt.Columns.Add("Lover");
dt.Columns.Add("Name");
DataRow dr = dt.NewRow();
dr["ID"] =1;
dr["Age"] ="Age1";
dr["Lover"] ="Lover1";
dr["Name"] ="Name1";
dt.Rows.Add(dr);
DataRow dr1 = dt.NewRow();
dr1["ID"] =2;
dr1["Age"] ="Age2";
dr1["Lover"] ="Lover2";
dr1["Name"] ="Name2";
dt.Rows.Add(dr1);
return dt;
}
}
}

C# 中 DataTable转换成IList的更多相关文章
- DataTable转换成IList
//文章出处: http://www.cnblogs.com/hlxs/archive/2011/05/09/2087976.html DataTable转换成IList 在用C#作开发的时候经常要把 ...
- DataTable转换成IList<T>的简单实现
DataTable的无奈 很多时候,我们需要去操作DataTable.但DataTable的操作,实在是太不方便了.Linq?lambda表达式?统统没有... 特别是对现有结果集做进一步筛选,这样的 ...
- DataTable转换成IList 【转载】
链接:http://www.cnblogs.com/hlxs/archive/2011/05/09/2087976.html#2738813 留着学习 using System; using Syst ...
- DataTable 转换成 Json的3种方法
在web开发中,我们可能会有这样的需求,为了便于前台的JS的处理,我们需要将查询出的数据源格式比如:List<T>.DataTable转换为Json格式.特别在使用Extjs框架的时候,A ...
- 将DataTable转换成CSV文件
DataTable用于在.net项目中,用于缓存数据,DataTable表示内存中数据的一个表.CSV文件最早用在简单的数据库里,由于其格式简单,并具备很强的开放性,所以起初被扫图家用作自己图集的标记 ...
- C#将DataTable转换成list的方法
本文实例讲述了C#将DataTable转换成list及数据分页的方法.分享给大家供大家参考.具体如下: /// <summary> /// 酒店评论列表-分页 /// </su ...
- 将list<对象>转换成DataTable,把DataTable转换成参数传入存储过程实现批量插入数据
领导让在存储过程中批量添加数据,找出效率最高的,我看到后台代码后,发现可以将list<对象>转换成DataTable,把DataTable转换成参数传入存储过程实现批量插入数据,知道还有其 ...
- 简单的反射 把datatable 转换成list对象
/// <summary> /// 把datatable 转换成list对象 /// </summary> /// <typeparam name="T&quo ...
- C# DataTable转换成实体列表 与 实体列表转换成DataTable
/// <summary> /// DataTable转换成实体列表 /// </summary> /// <typeparam name="T"&g ...
随机推荐
- MySQL open_files_limit相关设置
背景: 数据库链接不上,报错: root@localhost:/var/log/mysql# mysql -uzjy -p -h192.168.1.111 --default-charact ...
- centos7修改root根目录
1.拷贝/root 原目录的东西到新目录中(包括.xxx文件) /abc 2.修改配置文件 vi /etc/passwd root:x:0:0:root:/root:/bin/bash ==> ...
- shell 报错 /bin/bash^M: bad interpreter: No such file or directory
shell 执行报错: ./test.sh: /bin/bash^M: bad interpreter: No such file or directory 原因:window和linux 的文件格式 ...
- Le Chapitre VI
Ah! petit prince, j'ai compris, peu à peu, ainsi, ta petite vie mélancolique. Tu n'avais eu longtemp ...
- python知识积累
1. 安装requirements.txt依赖: pip install -r requirements.txt 生成requirements.txt文件: pip freeze > requi ...
- 已经安装了客户端,但是cmd输入sqlcmd报错:Sqlcmd:Error:Connection failure.SQL Native Client is not installed correctly
以前安装了sqlserver2008,没有卸载掉,后面又安装了sqlserver2014,所以系统环境变量中既有2008的环境变量的配置,又有2014的环境变量的配置,所以在终端输入sqlcmd时报错 ...
- nginx自动启动脚本
#!/bin/bash#nginx - this script starts and stops the nginx daemin # # chkconfig: - 85 15 # descripti ...
- maven打包某个分支的包
maven打某个分支的包命令: mvn clean install -Dmaven.test.skip=true -Pdevelop
- Linux下通过管道杀死所有与tomcat相关的进程
先将正确的命令放上来: ps -ef | grep ps -ef将系统中运行的进程展示出来 选择带有tomcat的进程后同时去除自身带有grep的进程,毕竟本身运行的这条命令是与tomcat相关的 a ...
- 链家web前端面试
共有三轮面试,每个面试官的第一个问题都是:介绍一个你觉着比较出彩的项目 第一轮面试: 因为公司项目没什么亮点,很传统的pc端,美女面试官就说让讲一下我用react的私人项目; 问了很多都是关于reac ...