C# DataTable,DataSet,IList,IEnumerable 互转扩展属性
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Reflection;
using System.Collections;
namespace XHSoft.LicenseManagerUI
{
/// <summary>
/// 扩展属性
/// </summary>
public static class Extensions
{
#region 数据集转换泛型集合扩展
/// <summary>
/// DataSet转换为泛型集合
/// </summary>
/// <typeparam name="T">泛型类型</typeparam>
/// <param name="ds">DataSet数据集</param>
/// <param name="tableIndex">待转换数据表索引,默认第0张表</param>
/// <returns>返回泛型集合</returns>
public static IList<T> ToList<T>(this DataSet ds, int tableIndex = 0)
{
if (ds == null || ds.Tables.Count < 0) return null;
if (tableIndex > ds.Tables.Count - 1)
return null;
if (tableIndex < 0)
tableIndex = 0;
DataTable dt = ds.Tables[tableIndex];
// 返回值初始化
IList<T> result = new List<T>();
for (int j = 0; j < dt.Rows.Count; j++)
{
T _t = (T)Activator.CreateInstance(typeof(T));
PropertyInfo[] propertys = _t.GetType().GetProperties();
foreach (PropertyInfo pi in propertys)
{
for (int i = 0; i < dt.Columns.Count; i++)
{
// 属性与字段名称一致的进行赋值
if (pi.Name.Equals(dt.Columns[i].ColumnName))
{
// 数据库NULL值单独处理
if (dt.Rows[j][i] != DBNull.Value)
pi.SetValue(_t, dt.Rows[j][i], null);
else
pi.SetValue(_t, null, null);
break;
}
}
}
result.Add(_t);
}
return result;
}
/// <summary>
/// DataTable转换为泛型集合
/// </summary>
/// <typeparam name="T">泛型类型</typeparam>
/// <param name="dt">DataTable数据表</param>
/// <returns>返回泛型集合</returns>
public static IList<T> ToList<T>(this DataTable dt) where T:class,new()
{
if (dt == null || dt.Rows.Count <= 0) return null;
List<T> list =new List<T>();
#region 方法一:
//T model;
//Type infos = typeof(T);
////object tempValue;
//foreach (DataRow dr in dt.Rows)
//{
// model = new T();
// 1.
// infos.GetProperties().ToList().ForEach(p =>p.SetValue(model, dr[p.Name], null));
// 2.
// //infos.GetProperties().ToList().ForEach(p =>
// //{
// // tempValue = dr[p.Name];
// // if (!string.IsNullOrEmpty(tempValue.ToString()))
// // p.SetValue(model, tempValue, null);
// //});
// list.Add(model);
//}
#endregion
#region 方法二: 比方法一快
PropertyInfo[] propertys = typeof(T).GetProperties();
for (int j = 0; j < dt.Rows.Count; j++)
{
T _t = (T)Activator.CreateInstance(typeof(T));
foreach (PropertyInfo pi in propertys)
{
// 属性与字段名称一致的进行赋值
if (pi.Name.Equals(dt.Columns[pi.Name].ColumnName))
{
if (dt.Rows[j][pi.Name] != DBNull.Value)
pi.SetValue(_t, dt.Rows[j][pi.Name], null);
else
pi.SetValue(_t, null, null);
}
}
list.Add(_t);
}
#endregion
return list;
}
/// <summary>
/// DataSet转换为泛型集合
/// </summary>
/// <typeparam name="T">泛型类型</typeparam>
/// <param name="ds">DataSet数据集</param>
/// <param name="tableName">待转换数据表名称,名称为空时默认第0张表</param>
/// <returns>返回泛型集合</returns>
public static IList<T> ToList<T>(this DataSet ds, string tableName)
{
int _TableIndex = 0;
if (ds == null || ds.Tables.Count < 0)
return null;
if (string.IsNullOrEmpty(tableName))
return ToList<T>(ds, 0);
for (int i = 0; i < ds.Tables.Count; i++)
{
// 获取Table名称在Tables集合中的索引值
if (ds.Tables[i].TableName.Equals(tableName))
{
_TableIndex = i;
break;
}
}
return ToList<T>(ds, _TableIndex);
}
#endregion
#region 泛型集合转换为数据集扩展
/// <summary>
/// 将泛型集合转换成DataSet数据集
/// </summary>
/// <typeparam name="T">T类型</typeparam>
/// <param name="list">泛型集合</param>
/// <returns>DataSet数据集</returns>
public static DataSet ToDataSet<T>(this IList<T> list)
{
Type elementType = typeof(T);
var ds = new DataSet();
var t = new DataTable();
ds.Tables.Add(t);
elementType.GetProperties().ToList().ForEach(propInfo => t.Columns.Add(propInfo.Name, Nullable.GetUnderlyingType(propInfo.PropertyType) ?? propInfo.PropertyType));
foreach (T item in list)
{
var row = t.NewRow();
elementType.GetProperties().ToList().ForEach(propInfo => row[propInfo.Name] = propInfo.GetValue(item, null) ?? DBNull.Value);
t.Rows.Add(row);
}
return ds;
}
/// <summary>
/// 泛型集合转换成DataTable表
/// </summary>
/// <typeparam name="T">T类型</typeparam>
/// <param name="list">泛型集合</param>
/// <returns>DataTable表</returns>
public static DataTable ToDataTable<T>(this IList<T> list)
{
return ToDataTable(list, null);
}
/// <summary>
/// 泛型集合转换成DataTable表
/// </summary>
/// <typeparam name="T">T类型</typeparam>
/// <param name="list">泛型集合</param>
/// <param name="_tableName">Table名称</param>
/// <returns>DataTable表</returns>
public static DataTable ToDataTable<T>(this IList<T> list, string _tableName)
{
Type elementType = typeof(T);
var dt = new DataTable();
if (_tableName == "null")
dt.TableName = _tableName;
elementType.GetProperties().ToList().ForEach(propInfo => dt.Columns.Add(propInfo.Name, Nullable.GetUnderlyingType(propInfo.PropertyType) ?? propInfo.PropertyType));
foreach (T item in list)
{
var row = dt.NewRow();
elementType.GetProperties().ToList().ForEach(propInfo => row[propInfo.Name] = propInfo.GetValue(item, null) ?? DBNull.Value);
dt.Rows.Add(row);
}
return dt;
}
#endregion
#region 以下为IEnumerable扩展实现
/// <summary>
/// 给非强类型的IEnumerable返回头一个元素。
/// </summary>
public static object First(this IEnumerable col)
{
foreach (var item in col)
return item;
throw new IndexOutOfRangeException();
}
/// <summary>
/// 给非强类型的IEnumerable返回头一个强类型的元素
/// </summary>
public static object First<T>(this IEnumerable col)
{
return (T)col.First();
}
/// <summary>
/// 基本上和List<T>的ForEach方法一致。
/// </summary>
public static void Each<T>(this IEnumerable<T> col, Action<T> handler)
{
foreach (var item in col)
handler(item);
}
/// <summary>
/// 带索引的遍历方法。
/// </summary>
public static void Each<T>(this IEnumerable<T> col, Action<T, int> handler)
{
int index = 0;
foreach (var item in col)
handler(item, index++);
}
/// <summary>
/// 可以半途中断执行的遍历方法。
/// </summary>
public static void Each<T>(this IEnumerable<T> col, Func<T, bool> handler)
{
foreach (var item in col)
if (!handler(item)) break;
}
/// <summary>
/// 可以半途中段的带索引的遍历方法。
/// </summary>
public static void Each<T>(this IEnumerable<T> col, Func<T, int, bool> handler)
{
int index = 0;
foreach (var item in col)
if (!handler(item, index++)) break;
}
#endregion
#region 以下为IEnumerable<T>的非泛型实现
public static void Each<T>(this IEnumerable col, Action<object> handler)
{
foreach (var item in col)
handler(item);
}
public static void Each<T>(this IEnumerable col, Action<object, int> handler)
{
int index = 0;
foreach (var item in col)
handler(item, index++);
}
public static void Each<T>(this IEnumerable col, Func<object, bool> handler)
{
foreach (var item in col)
if (!handler(item)) break;
}
public static void Each<T>(this IEnumerable col, Func<object, int, bool> handler)
{
int index = 0;
foreach (var item in col)
if (!handler(item, index++)) break;
}
#endregion
}
}
C# DataTable,DataSet,IList,IEnumerable 互转扩展属性的更多相关文章
- C#高效导出Excel(IList转DataTable,DataSet)
微软的Excel操作类导出Excel会很慢,此方法简单的把表中内容以字符串的形式写入到Excel中,用到的一个技巧就是"\t". C#中的\t相当于Tab键,写入到Excel中时就 ...
- DataTable,List,Dictonary互转,筛选及相关写法
1.创建自定义DataTable /// 创建自定义DataTable(一) 根据列名字符串数组, /// </summary> /// <param name="sLi ...
- DataTable 和Json 字符串互转
#region DataTable 转换为Json字符串实例方法 /// <summary> /// GetClassTypeJosn 的摘要说明 /// </summary> ...
- DateTable与List<T>相互转换 及JSON与DataTable(DataSet)相互转化
http://www.360doc.com/content/13/0712/09/10504424_299336674.shtml Linq处理List数据 http://blog.163.com/l ...
- Newtonsoft.Json高级用法DataContractJsonSerializer,JavaScriptSerializer 和 Json.NET即Newtonsoft.Json datatable,dataset,modle,序列化
原文地址:https://www.cnblogs.com/yanweidie/p/4605212.html Newtonsoft.Json介绍 在做开发的时候,很多数据交换都是以json格式传输的.而 ...
- Newtonsoft.Json高级用法,json序列号,model反序列化,支持序列化和反序列化DataTable,DataSet,Entity Framework和Entity,字符串
原文地址:https://www.cnblogs.com/yanweidie/p/4605212.html 手机端应用讲究速度快,体验好.刚好手头上的一个项目服务端接口有性能问题,需要进行优化.在接口 ...
- 完整DataTable与IList互换(转)
public class CollectionHelper { private CollectionHelper() { } public static DataTable ConvertTo< ...
- IEnumerable接口的扩展方法
/// <summary>/// IEnumerable接口的扩展方法,支持它的实现类是List的情况/// </summary>using System.Collection ...
- DataTable和List集合互转
/// <summary> /// 将集合转换成DataTable /// </summary> /// <param name="list"> ...
随机推荐
- Android初级教程:RatingBar的使用
记得淘宝里面买家给卖家评分的时候会有一个星星状的评分条,其实就是基于RatingBar做了自定义使用了.那么本篇文章就对RatingBar的使用做一个基本的认识. 接下来就是正题,那就是对于Ratin ...
- 关于ROS学习的一些反思
距离发布上一篇ROS的博客已经过去两年了,才发现原来自己已经这么久可没有写过关于ROS的文章,想来很是惭愧.这两年时间,自己怀着程序员的梦想,研究过RTOS,探索过Linux,编写过Android应用 ...
- Java基本语法-----java函数
函数的概述 发现不断进行加法运算,为了提高代码的复用性,就把该功能独立封装成一段独立的小程序,当下次需要执行加法运算的时候,就可以直接调用这个段小程序即可,那么这种封装形形式的具体表现形式则称作函数. ...
- sql server中高并发情况下 同时执行select和update语句死锁问题 (二)
SQL Server死锁使我们经常遇到的问题,数据库操作的死锁是不可避免的,本文并不打算讨论死锁如何产生,重点在于解决死锁.希望对您学习SQL Server死锁方面能有所帮助. 死锁对于DBA或是数据 ...
- 在Linux环境下实现一个非常好的bash脚本框架
为了方便我日常工作中的编译环境,免去我敲命令行所浪费的时间,我个人写了一个非常有用而又简单的脚本框架,该框架即可以完成的工程源码编译,也可以清除,拷贝等等操作,具体需要开发者自己来实现细节,我的框架思 ...
- 1089. Insert or Merge (25)
题目如下: According to Wikipedia: Insertion sort iterates, consuming one input element each repetition, ...
- UNIX网络编程——Socket通信原理和实践
我们深谙信息交流的价值,那网络中进程之间如何通信,如我们每天打开浏览器浏览网页时,浏览器的进程怎么与web服务器通信的?当你用QQ聊天时,QQ进程怎么与服务器或你好友所在的QQ进程通信?这些都得靠so ...
- Android计时器Chronometer-android学习之旅(二十一)
Chronometer简介 Chronometer和DigitalColok都继承与TextView,但是Chronometer不是显示的当前时间,而是从某个时间开始又过去了多少时间,是一个时间差. ...
- springMVC源码分析--国际化实现Session和Cookie(二)
上一篇博客springMVC源码分析--国际化LocaleResolver(一)中我们介绍了springMVC提供的国际化的解决方案,接下来我们根据springMVC提供的解决方案来简单的实现一个多语 ...
- Android的数字选择器NumberPicker-android学习之旅(三十七)
我想说的话 今天晚上我依然在图书馆写博客,其实此刻我的没心激动而忐忑,因为明天就是足球赛的决赛,我作为主力球员压力很大,因对对方很强大,但是那又怎么样.so what...我不会停止写博客的 Numb ...