public class DataHelper
{
//datarow 转换的类型缓存
private static MemoryCache modelCash = MemoryCache.Default; /// <summary>
/// 将DataTable集合转换为指定的对象集合
/// </summary>
/// <typeparam name="T">要转换成的对象类型</typeparam>
/// <param name="dt">DataTable数据集合</param>
/// <returns>指定的对象集合</returns>
public static List<T> DataTableToList<T>(DataTable dt)
where T : new()
{
var modelList = new List<T>();
int rowsCount = dt.Rows.Count;
if (rowsCount > )
{
for (int n = ; n < rowsCount; n++)
{
var model = DataRowToModel<T>(dt.Rows[n]);
modelList.Add(model);
}
} return modelList;
} /// <summary>
/// 将DataRow数据转换为指定的对象
/// </summary>
public static T DataRowToModel<T>(DataRow dr)
where T : new()
{
if (dr == null) return default(T); var isResetCash = false;
var model = new T();
var propertyHt = GetCashValue(model.GetType().Name) ?? new Hashtable(); for (var i = ; i < dr.Table.Columns.Count; i++)
{
var fieldName = dr.Table.Columns[i].ColumnName;
var property = GetProperty(ref isResetCash, model, propertyHt, fieldName); if (property != null)
{
var fullName = property.PropertyType.FullName;
if (fullName.Contains("Guid"))
{
if (!string.IsNullOrEmpty(dr[fieldName].ToString()))
property.SetValue(model, new Guid(dr[fieldName].ToString()), null);
else
property.SetValue(model, null, null);
}
else if (fullName.Contains("Double"))
{
if (!string.IsNullOrEmpty(dr[fieldName].ToString()))
property.SetValue(model, double.Parse(dr[fieldName].ToString()), null);
else
property.SetValue(model, null, null);
}
else if (fullName.Contains("Int32"))
{
if (!string.IsNullOrEmpty(dr[fieldName].ToString()))
property.SetValue(model, int.Parse(dr[fieldName].ToString()), null);
else
property.SetValue(model, null, null);
}
else if (fullName.Contains("System.DateTime"))
{
if (!string.IsNullOrEmpty(dr[fieldName].ToString()))
property.SetValue(model, Convert.ToDateTime(dr[fieldName]), null);
else
property.SetValue(model, null, null);
}
else if (fullName.Contains("System.Byte"))
{
if (!string.IsNullOrEmpty(dr[fieldName].ToString()))
property.SetValue(model, dr[fieldName], null);
else
property.SetValue(model, null, null);
}
else if (fullName.Contains("System.Boolean"))
{
if (!string.IsNullOrEmpty(dr[fieldName].ToString()))
property.SetValue(model, dr[fieldName], null);
else
property.SetValue(model, null, null);
}
else if (fullName.Contains("System.Single"))
{
if (!string.IsNullOrEmpty(dr[fieldName].ToString()))
property.SetValue(model, dr[fieldName], null);
else
property.SetValue(model, null, null);
}
else
{
property.SetValue(model, dr[fieldName].ToString(), null);
}
}
} if (isResetCash) SetCashValue(model.GetType().Name, propertyHt);
return model;
} private static PropertyInfo GetProperty<T>(ref bool isResetCash, T model, Hashtable propertyHt, string fieldName)
{
PropertyInfo property = null;
if (propertyHt != null)
{
if (propertyHt.ContainsKey(fieldName))
{
property = propertyHt[fieldName] as PropertyInfo;
}
else
{
property = model.GetType().GetProperty(fieldName);
if (property != null)
{
propertyHt[fieldName] = property;
isResetCash = true;
}
}
}
else
{
property = model.GetType().GetProperty(fieldName);
if (property != null)
{
propertyHt[fieldName] = property;
isResetCash = true;
}
} return property;
} private static Hashtable GetCashValue(string key)
{
if (modelCash.Contains(key))
{
return modelCash[key] as Hashtable;
}
return null;
} private static void SetCashValue(string key, Hashtable value)
{
CacheItemPolicy cip = new CacheItemPolicy()
{
AbsoluteExpiration = new DateTimeOffset(DateTime.Now.AddMinutes( * * ))
}; modelCash.Set(key, value, cip);
}
}

public class DataHelper    {        //datarow 转换的类型缓存        private static MemoryCache modelCash = MemoryCache.Default;
        /// <summary>        /// 将DataTable集合转换为指定的对象集合        /// </summary>        /// <typeparam name="T">要转换成的对象类型</typeparam>        /// <param name="dt">DataTable数据集合</param>        /// <returns>指定的对象集合</returns>        public static List<T> DataTableToList<T>(DataTable dt)             where T : new()        {            var modelList = new List<T>();            int rowsCount = dt.Rows.Count;            if (rowsCount > 0)            {                for (int n = 0; n < rowsCount; n++)                {                    var model = DataRowToModel<T>(dt.Rows[n]);                    modelList.Add(model);                }            }
            return modelList;        }
        /// <summary>        /// 将DataRow数据转换为指定的对象        /// </summary>        public static T DataRowToModel<T>(DataRow dr)             where T : new()        {            if (dr == null) return default(T);
            var isResetCash = false;            var model = new T();            var propertyHt = GetCashValue(model.GetType().Name) ?? new Hashtable();
            for (var i = 0; i < dr.Table.Columns.Count; i++)            {                var fieldName = dr.Table.Columns[i].ColumnName;                var property = GetProperty(ref isResetCash, model, propertyHt, fieldName);
                if (property != null)                {                    var fullName = property.PropertyType.FullName;                    if (fullName.Contains("Guid"))                    {                        if (!string.IsNullOrEmpty(dr[fieldName].ToString()))                            property.SetValue(model, new Guid(dr[fieldName].ToString()), null);                        else                            property.SetValue(model, null, null);                    }                    else if (fullName.Contains("Double"))                    {                        if (!string.IsNullOrEmpty(dr[fieldName].ToString()))                            property.SetValue(model, double.Parse(dr[fieldName].ToString()), null);                        else                            property.SetValue(model, null, null);                    }                    else if (fullName.Contains("Int32"))                    {                        if (!string.IsNullOrEmpty(dr[fieldName].ToString()))                            property.SetValue(model, int.Parse(dr[fieldName].ToString()), null);                        else                            property.SetValue(model, null, null);                    }                    else if (fullName.Contains("System.DateTime"))                    {                        if (!string.IsNullOrEmpty(dr[fieldName].ToString()))                            property.SetValue(model, Convert.ToDateTime(dr[fieldName]), null);                        else                            property.SetValue(model, null, null);                    }                    else if (fullName.Contains("System.Byte"))                    {                        if (!string.IsNullOrEmpty(dr[fieldName].ToString()))                            property.SetValue(model, dr[fieldName], null);                        else                            property.SetValue(model, null, null);                    }                    else if (fullName.Contains("System.Boolean"))                    {                        if (!string.IsNullOrEmpty(dr[fieldName].ToString()))                            property.SetValue(model, dr[fieldName], null);                        else                            property.SetValue(model, null, null);                    }                    else if (fullName.Contains("System.Single"))                    {                        if (!string.IsNullOrEmpty(dr[fieldName].ToString()))                            property.SetValue(model, dr[fieldName], null);                        else                            property.SetValue(model, null, null);                    }                    else                    {                        property.SetValue(model, dr[fieldName].ToString(), null);                    }                }            }
            if (isResetCash) SetCashValue(model.GetType().Name, propertyHt);            return model;        }
        private static PropertyInfo GetProperty<T>(ref bool isResetCash, T model, Hashtable propertyHt, string fieldName)        {            PropertyInfo property = null;            if (propertyHt != null)            {                if (propertyHt.ContainsKey(fieldName))                {                    property = propertyHt[fieldName] as PropertyInfo;                }                else                {                    property = model.GetType().GetProperty(fieldName);                    if (property != null)                    {                        propertyHt[fieldName] = property;                        isResetCash = true;                    }                }            }            else            {                property = model.GetType().GetProperty(fieldName);                if (property != null)                {                    propertyHt[fieldName] = property;                    isResetCash = true;                }            }
            return property;        }
        private static Hashtable GetCashValue(string key)        {            if (modelCash.Contains(key))            {                return modelCash[key] as Hashtable;            }            return null;        }
        private static void SetCashValue(string key, Hashtable value)        {            CacheItemPolicy cip = new CacheItemPolicy()            {                AbsoluteExpiration = new DateTimeOffset(DateTime.Now.AddMinutes(30 * 24 * 60))            };
            modelCash.Set(key, value, cip);        }    }

datatable to List<T>带缓存的更多相关文章

  1. 带缓存的输入输出-bufferedinputstream类与bufferedoutputstream类

    package hengzhe.cn.o1; import java.io.*; /* * 带缓存的输入输出-bufferedinputstream类与bufferedoutputstream类 * ...

  2. 不带缓存的I/O和标准(带缓存的)I/O

    首先,先稍微了解系统调用的概念:       系统调用,英文名system call,每个操作系统都在内核里有一些内建的函数库,这些函数可以用来完成一些系统系统调用把应用程序的请求传给内核,调用相应的 ...

  3. 基于AFN封装的带缓存的网络请求

    给大家分享一个基于AFN封装的网络请求 git: https://github.com/zhouxihi/NVNetworking #带缓存机制的网络请求 各类请求有分带缓存 , 不带缓存, 可自定义 ...

  4. Delphi中带缓存的数据更新技术

    一. 概念 在网络环境下,数据库应用程序是c/s或者是多层结构的模式.在这种环境下,数据库应用程序的开发应当尽可能考虑减少网络数据传输量,并且尽量提高并发度.基于这个目的,带缓存的数据更新技术应运而生 ...

  5. 带标准IO带缓存区和非标准IO 遇到fork是的情况分析

    废话不多说 直接代码 #include<stdio.h> #include<sys/types.h> #include<unistd.h> #include< ...

  6. 不带缓存IO和标准(带缓存)IO

    linux对IO文件的操作分为: 不带缓存:open read.posix标准,在用户空间没有缓冲,在内核空间还是进行了缓存的.数据-----内核缓存区----磁盘 假设内核缓存区长度为100字节,你 ...

  7. 使用TP自带缓存时。出现第一次拿不到数据。

    使用TP自带缓存时.出现第一次拿不到数据. 仔细检查逻辑发现了问题所在. 逻辑:直接读缓存,如果没有从数据库查询,然后存入缓存. 问题出在以为$exchange = S($fileName,$exch ...

  8. 带缓存的基于DateTimeFormatter的日期格式化工具类

    JAVA中的SimpleDateFormat是非线程安全的,所有在1.8的JDK版本里提供了线程安全的DateTimeFormatter类,由于是线程安全的,故我们可以将此类缓存起来多次利用提高效率. ...

  9. Yii的自带缓存的使用

    Yii的自带缓存都继承CCache 类, 在使用上基本没有区别缓存基础类 CCache 提供了两个最常用的方法:set() 和 get().要在缓存中存储变量 $value,我们选择一个唯一 ID 并 ...

随机推荐

  1. linux上安装mysql,亲试成功

    安装mysql参考 网址https://blog.csdn.net/a774630093/article/details/79270080 本文更加详细. 1.先检查系统是否装有mysql rpm - ...

  2. 3ds max学习笔记(八)-- 实例操作(直行楼梯)

    1.选择要复制的物体,执行[工具]/[阵列]命令,弹出对话框: 2.参数说明: 应用: 1.[自定义]/[单位设置],将单位改为mm 在顶视图中,创建长方体,长1600,宽300,高度150 2.在前 ...

  3. 创建xml文件、解析xml文件

        1.创建XML文件: import codecs import xml.dom.minidom doc=xml.dom.minidom.Document() print doc root=do ...

  4. ORM字段操作

    django orm 建表字段 在django modle 中,我们定义的类,他的对象就是数据库表中的一行数据!!! django orm 基础 一:modle的各个字段: 在python中以code ...

  5. SharePoint 读取内容的插件之SharepointPlus

    前言 最近,一直在前端和SharePoint进行交互,然后,发现一个好用的插件,分享给大家. 首先,需要添加一个引用,如下图: 当然,我这里只是举个例子,亲们一定要去下载这个库,然后传到服务器或者文档 ...

  6. SSE图像算法优化系列二十三: 基于value-and-criterion structure 系列滤波器(如Kuwahara,MLV,MCV滤波器)的优化。

    基于value-and-criterion structure方式的实现的滤波器在原理上其实比较简单,感觉下面论文中得一段话已经描述的比较清晰了,直接贴英文吧,感觉翻译过来反而失去了原始的韵味了. T ...

  7. jquery动态添加元素无法触发绑定的事件的解决方案

    方法一:绑定live事件(live事件只在jquery1.9以下才支持,高版本不支持). //jquery 1.9(不包括1.9)以下可以 $(".btn").live(" ...

  8. linux apache2部署php

    apache2 doc http://blog.csdn.net/actor1999/article/details/44802519 #apache sudo apt-get install apa ...

  9. TensorFlow保存和载入模型

    首先定义一个tf.train.Saver类: saver = tf.train.Saver(max_to_keep=1) 其中,max_to_keep参数设定只保存最后一个参数,默认值是5,即保存最后 ...

  10. 【一步步学OpenGL 20】 -《点光源》

    教程 20 点光源 原文: http://ogldev.atspace.co.uk/www/tutorial20/tutorial20.html CSDN完整版专栏: http://blog.csdn ...