DataTable转换成IList
//文章出处:
http://www.cnblogs.com/hlxs/archive/2011/05/09/2087976.html
在用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
{
public class 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)
{
return null;
}
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)
{
return null;
} 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);
}
else if (p.PropertyType == typeof(int))
{
p.SetValue(model, int.Parse(dr[colNames[i++]].ToString()), null);
}
else if (p.PropertyType == typeof(DateTime))
{
p.SetValue(model, DateTime.Parse(dr[colNames[i++]].ToString()), null);
}
else if (p.PropertyType == typeof(float))
{
p.SetValue(model, float.Parse(dr[colNames[i++]].ToString()), null);
}
else if (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>
private string GetKey(string val, Hashtable tb)
{
foreach (DictionaryEntry de in tb)
{
if (de.Value.ToString() == val)
{
return de.Key.ToString();
}
}
return null;
} }
} namespace TBToListTest
{ //实体
public class Person
{
public int ID
{
set;
get;
} public string Name
{
set;
get;
} public string Age
{
set;
get;
} public string Lover
{
set;
get;
} }
} using System;
using System.Data; namespace TBToListTest
{
class Program
{
static void Main(string[] args)
{
TBToList<Person> tol = new TBToList<Person>();
Console.WriteLine();
DataTable dt = GetTable();
tol.ToList(dt);
Console.Read();
} public static 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;
}
}
}
DataTable转换成IList的更多相关文章
- DataTable转换成IList<T>的简单实现
DataTable的无奈 很多时候,我们需要去操作DataTable.但DataTable的操作,实在是太不方便了.Linq?lambda表达式?统统没有... 特别是对现有结果集做进一步筛选,这样的 ...
- C# 中 DataTable转换成IList
在用C#作开发的时候经常要把DataTable转换成IList:操作DataTable比较麻烦,把DataTable转换成IList,以对象实体作为IList的元素,操作起来就非常方便. 注意:实体的 ...
- DataTable转换成IList 【转载】
链接:http://www.cnblogs.com/hlxs/archive/2011/05/09/2087976.html#2738813 留着学习 using System; using Syst ...
- C# DataTable转换成实体列表 与 实体列表转换成DataTable
/// <summary> /// DataTable转换成实体列表 /// </summary> /// <typeparam name="T"&g ...
- DataTable转换成匿名类的List类型
DataTable转换成匿名类的List类型 因为匿名类是不能够 Activator.CreateInstance进行反射实例化的 /// <summary> /// 匿名类的转换方式 ...
- DataTable 转换成 Json的3种方法
在web开发中,我们可能会有这样的需求,为了便于前台的JS的处理,我们需要将查询出的数据源格式比如:List<T>.DataTable转换为Json格式.特别在使用Extjs框架的时候,A ...
- asp.net dataTable转换成Json格式
/// <summary> /// dataTable转换成Json格式 /// </summary> /// <param name="dt"> ...
- 将DataTable转换成CSV文件
DataTable用于在.net项目中,用于缓存数据,DataTable表示内存中数据的一个表.CSV文件最早用在简单的数据库里,由于其格式简单,并具备很强的开放性,所以起初被扫图家用作自己图集的标记 ...
- 将DataSet(DataTable)转换成JSON格式(生成JS文件存储)
public static string CreateJsonParameters(DataTable dt) { /**/ /**/ /**/ /* /*********************** ...
随机推荐
- 一稿设计多端适配优雅的解决方案 - rem
规范目的 为提高前端团队开发效率,输出高质量的前端页面代码,提高UI设计还原度,特编写该规范文档.本文档如有不对或者不合适的地方请及时提出. JS代码块 (function (doc, win) { ...
- 编程之美 海量数据寻找 K 大数
1. 使用最小堆, 设置最小堆的大小为K, 仅需遍历一遍即可 2. 寻找最大的 K 个数实质上是寻找第 K 大的数. 通过二分法在区间内不断校正 mid 的值来找到 pivot, 时间复杂度为 o(N ...
- C static 关键字理解
今天来看一下这么一个程序. #include<stdio.h> int count =1; int fun(void) { static int count =10; return cou ...
- Python学习笔记6-字典Dict
Python内置了字典:dict的支持,dict全称dictionary,在其他语言中也称为map,使用键-值(key-value)存储,具有极快的查找速度. >>> person ...
- JSON-Server 安装
在后台还没给接口之前,使用JSON-Server搭建一台JSON服务器,将接口要返回的数据放在json文件里面.然后请求这些数据,这样我们可以先做一些东西,等后台接口好了之后直接替换就可以了,不必一直 ...
- Android 全局异常处理(三)
用过安卓手机的用户以及安卓开发者们会时长碰到程序异常退出的情况,普通用户遇到这种情况,肯定非常恼火,甚至会骂一生垃圾软件,然后卸载掉.那么开发者们在开发过程中遇到这种情况给怎么办呢,当然,你不可能世界 ...
- XXL-JOB分布式任务调度平台安装与部署
配XXL-JOB分布式任务调度平台安装与部署
- 用wamp实现前端和php的交互效果
我们今天来用php来做一下前台与后台的交互效果,首先我们先打开这个软件. 看一下电脑右下角的小图标 当变成之后鼠标左键 打开这个之后点击第二个之后会打开一个网站 点击右面页面的数据库打开新建数据库,填 ...
- FZU 2140 Forever 0.5(找规律,几何)
Problem 2140 Forever 0.5 Accept: 371 Submit: 1307 Special Judge Time Limit: 1000 mSec Memory Limit : ...
- 遇到的问题mongodb
1.MongoNetworkError:failed to connect to server? 数据库没有启动,启动mongo数据库就好 2.有些东西真的是要做好记录的,单纯为了自己日后可以查阅比较 ...