/**********************************************************************************/
// 说明: 数据转换工具.
// 注意: 对象列表转换为DataTable或DataTable转换为对象列表.
// 字段参照由对象的PropertyName决定.
// 数据模型类的属性名必需与字段名一致, 包括大小写一致.
/**********************************************************************************/ using System;
using System.Reflection;
using System.Collections;
using System.Data;
using System.Collections.Generic;
using System.Text;
using System.ComponentModel;
using System.Xml;
using System.Web.UI; namespace vjsdn.converter
{
public class CDataConvert
{ /// <summary>
/// 根据类创建表结构
/// </summary>
/// <param name="t"></param>
/// <returns></returns>
public static DataTable CreateTable(Type t)
{
return BuiltTable(t.GetProperties());
} /// <summary>
/// 根据对象的属性创建数据表
/// </summary>
private static DataTable BuiltTable(PropertyInfo[] pinfo)
{
try
{
if (pinfo == null) return null;
DataTable table = new DataTable();
foreach (PropertyInfo info in pinfo)
{
Type type = info.PropertyType;
if (info.PropertyType.IsGenericType)
type = info.PropertyType.GetGenericArguments()[];
DataColumn column = new DataColumn(info.Name, type);
column.AllowDBNull = true;
table.Columns.Add(column);
}
return table;
}
catch { return null; }
} /// <summary>
/// Object to Object. 将一个对象转换为指定类型的对象.
/// 注意: destination内的Property必需在source内存在.
/// </summary>
public static object CopyProperties(object source, Type destination)
{
try
{
if (source == null) return null;
object destObj = destination.Assembly.CreateInstance(destination.FullName);
PropertyInfo[] propsDest = destObj.GetType().GetProperties();
foreach (PropertyInfo infoDest in propsDest)
{
object value = GetValueOfObject(source, infoDest.Name);
if (CanShallowCopyProperty(value)) SetPropertyValue(destObj, infoDest, value);
}
return destObj;
}
catch { return null; }
} /// <summary>
/// 指定参数是否可用于浅拷贝
/// </summary>
private static bool CanShallowCopyProperty(object propValue)
{
if (propValue == null) return true;
if (propValue.GetType().IsValueType || propValue is string) return true;
return false;
} /// <summary>
/// 复制对象属性.
/// </summary>
public static void CopyProperties(object source, object destObj)
{
try
{
if (source == null || destObj == null) return;
PropertyInfo[] propsDest = destObj.GetType().GetProperties();
foreach (PropertyInfo infoDest in propsDest)
{
object value = GetValueOfObject(source, infoDest.Name);
if (CanShallowCopyProperty(value)) SetPropertyValue(destObj, infoDest, value);
}
}
catch { }
} /// <summary>
/// 复制对象. 浅拷贝.
/// </summary>
public static object CloneObject(object source)
{
try
{
if (source == null) return null;
Type objType = source.GetType();
object destObj = objType.Assembly.CreateInstance(objType.FullName);
PropertyInfo[] propsSource = objType.GetProperties();
foreach (PropertyInfo infoSource in propsSource)
{
object value = GetValueOfObject(source, infoSource.Name);
if (CanShallowCopyProperty(value)) SetPropertyValue(destObj, infoSource, value);
}
return destObj;
}
catch { return null; }
} /// <summary>
/// 复制一个对象数组.
/// </summary>
public static ArrayList CloneObjects(IList source)
{
if (source == null) return null;
ArrayList ret = new ArrayList();
foreach (object o in source) ret.Add(CloneObject(o));
return ret;
} /// <summary>
/// 获取对象指定属性的值
/// </summary>
public static object GetValueOfObject(object obj, string property)
{
try
{
if (obj == null) return null;
Type type = obj.GetType();
PropertyInfo[] pinfo = type.GetProperties();
foreach (PropertyInfo info in pinfo)
{
if (info.Name.ToUpper() == property.ToUpper())
return info.GetValue(obj, null);
}
return null;
}
catch { return null; }
} /// <summary>
/// 纵对象数据组取出某一个对象. 返回对象指定属性名称(returnPropName)的值
/// </summary>
public static object GetObjectValueByKey(IList objects, string keyPropName, object keyValue, string returnPropName)
{
object o = GetObjectByKey(objects, keyPropName, keyValue);
if (o != null)
return GetValueOfObject(o, returnPropName);
else
return null;
} /// <summary>
/// 纵对象数据组取出某一个对象. 参数指定关键字段名称(keyPropName)及值(keyValue).
/// </summary>
public static object GetObjectByKey(IList objects, string keyPropName, object keyValue)
{
foreach (object o in objects)
{
object value = GetValueOfObject(o, keyPropName);
if (value == null) continue;
if (value.ToString().ToLower() == keyValue.ToString().ToLower())
{
return o;
}
}
return null;
} /// <summary>
/// 查找对象包含指定属性.
/// </summary>
public static bool FindProperty(object obj, string property)
{
try
{
if (obj == null) return false;
Type type = obj.GetType();
PropertyInfo[] pinfo = type.GetProperties();
foreach (PropertyInfo info in pinfo)
{
if (info.Name.ToUpper() == property.ToUpper())
return true;
}
return false;
}
catch { return false; }
} public static void SetValueofDataRow(DataRow dr, string field, object value)
{
try
{
if (dr == null) return;
dr[field] = value; }
catch
{ }
} /// <summary>
/// 设置对象某个属性的值
/// </summary>
public static void SetValueOfObject(object obj, string property, object value)
{
try
{
if (obj == null) return;
Type type = obj.GetType();
PropertyInfo[] pinfo = type.GetProperties();
foreach (PropertyInfo info in pinfo)
{
if (info.Name.ToUpper() == property.ToUpper())
{
SetPropertyValue(obj, info, value);
break;
}
}
}
catch { }
} public static void SetPropertyValue(object instance, PropertyInfo prop, object value)
{
try
{
if (prop == null) return;
if (prop.PropertyType.ToString() == "System.String")
{ }
else if (prop.PropertyType.ToString() == "System.Decimal")
value = Decimal.Parse(value.ToString());
else if (prop.PropertyType.ToString() == "System.Int32")
value = int.Parse(value.ToString());
else if (prop.PropertyType.ToString() == "System.Single")
value = Single.Parse(value.ToString());
else if (prop.PropertyType.ToString() == "System.DateTime")
value = DateTime.Parse(value.ToString());
prop.SetValue(instance, value, null);
}
catch { }
} public static IList CSharpDataTypes()
{
ArrayList list = new ArrayList();
list.Add(typeof(System.DateTime));
list.Add(typeof(System.Byte));
list.Add(typeof(System.SByte));
list.Add(typeof(System.Int16));
list.Add(typeof(System.Int32));
list.Add(typeof(System.Int64));
list.Add(typeof(System.IntPtr));
list.Add(typeof(System.UInt16));
list.Add(typeof(System.UInt32));
list.Add(typeof(System.UInt64));
list.Add(typeof(System.UIntPtr));
list.Add(typeof(System.Single));
list.Add(typeof(System.Double));
list.Add(typeof(System.Decimal));
list.Add(typeof(System.Boolean));
list.Add(typeof(System.Char));
list.Add(typeof(System.String));
return list;
} /// <summary>
/// 根据IList对象创建数据表
/// </summary>
public static DataTable IListToDataTable(IList list)
{
try
{
if (list == null) return null;
if (list.Count <= ) return null;
Type type = list[].GetType();
PropertyInfo[] pinfo = type.GetProperties(); DataTable table = BuiltTable(pinfo);//创建表
DataRow row = null;
foreach (object o in list)
{
row = table.NewRow();
foreach (PropertyInfo info in pinfo)
{
object v = info.GetValue(o, null);
if (!ColumnExists(table, info.Name)) continue;
if (null == v)
row[info.Name] = DBNull.Value;
else
row[info.Name] = v;
}
table.Rows.Add(row);
}
return table;
}
catch { return null; }
} public static bool ColumnExists(DataTable dt, string columnName)
{
if (dt == null) return false;
foreach (DataColumn col in dt.Columns)
{
if (col.ColumnName.ToLower() == columnName.ToLower())
return true;
}
return false;
} /// <summary>
/// 数据表转换为IList对象,Type参数:对象类型
/// </summary>
public static IList DataTableToIList(DataTable table, Type type)
{
try
{
if (table == null) return null;
IList list = new object[table.Rows.Count];
object o = null;
PropertyInfo[] pinfo = type.GetProperties();
int idx = ;
foreach (DataRow row in table.Rows)
{
o = type.Assembly.CreateInstance(type.FullName);
foreach (PropertyInfo info in pinfo)
{
SetPropertyValue(o, info, GetFieldValue(row, info.Name));
}
list[idx] = o;
idx += ;
}
return list;
}
catch { return null; }
} /// <summary>
/// 根据对象的属性取字段的值
/// </summary>
private static object GetFieldValue(DataRow row, string propertyName)
{
if (row == null) return null;
if (row.Table.Columns.IndexOf(propertyName) >= )
{
object value = row[propertyName];
if (value != null && value is DateTime)
{
if ((DateTime)value <= DateTime.MinValue.AddDays())
value = null;
}
return value;
}
return null;
} public static DataRow UpdateDataRowFromObject(DataRow row, object o)
{
PropertyInfo[] pinfo = o.GetType().GetProperties();
foreach (PropertyInfo info in pinfo)
{
if (row.Table.Columns.IndexOf(info.Name) >= )
row[info.Name] = info.GetValue(o, null);
}
return row;
} public static DataRow AddDataRowFromObject(DataTable dt, object o)
{
DataRow row = dt.NewRow();
PropertyInfo[] pinfo = o.GetType().GetProperties();
foreach (PropertyInfo info in pinfo)
{
if (dt.Columns.IndexOf(info.Name) >= )
row[info.Name] = info.GetValue(o, null);
}
dt.Rows.Add(row);
return row;
} public static void SetTwoRowValues(DataRow rowFrom, DataRow rowTo)
{
for (int i = ; i < rowFrom.Table.Columns.Count; i++)
{
rowTo[i] = rowFrom[i];
}
} /// <summary>
/// 从源行中对相同字段名的列付值
/// </summary>
/// <param name="drSouce"></param>
/// <param name="drTo"></param>
public static void SetTwoRowSameColValue(DataRow drSource, DataRow drTo)
{
for (int i = ; i < drSource.Table.Columns.Count; i++)
{
string fieldname = drSource.Table.Columns[i].ColumnName;
DataColumn col = drTo.Table.Columns[fieldname];
if (col != null)
{
drTo[fieldname] = drSource[fieldname];
}
} } /// <summary>
/// 数据行(DataRow)转换为对象,对象的Type由type参数决定.
/// </summary>
public static object DataRowToObject(DataRow row, Type type)
{
if (null == row) return null;
try
{
object o = type.Assembly.CreateInstance(type.FullName);
PropertyInfo[] pinfo = type.GetProperties();
foreach (PropertyInfo info in pinfo)
{
//字段名称与对象属性相符才赋值
if (row.Table.Columns.IndexOf(info.Name) >= )
{
object v = GetFieldValue(row, info.Name);
SetPropertyValue(o, info, v);
}
}
return o;
}
catch { return null; }
} /// <summary>
/// ArrayList转换为对象数组.
/// </summary>
public static object[] ToObjects(IList source)
{
if (null == source) return null;
object[] ret = new object[source.Count];
for (int i = ; i < source.Count; i++) ret[i] = source[i];
return ret;
} /// <summary>
/// 对象数组转换为ArrayList.
/// </summary>
public static ArrayList ToArrayList(IList list)
{
if (list == null) return null;
ArrayList arrlist = new ArrayList();
foreach (object o in list) arrlist.Add(o);
return arrlist;
} /// <summary>
/// 对象数组转换为ArrayList.
/// </summary>
public static ArrayList ToArrayList(object[] source)
{
if (null != source)
return new ArrayList((ICollection)source);
else //如果来源数据为null,返回一个空的ArrayList.
return new ArrayList();
} /// <summary>
/// 把字符串以逗号分格,转换成数据库格式in('a','b')
/// </summary>
/// <param name="input"></param>
/// <returns></returns>
public static string ToSQLInDataFormat(string input)
{
string HQL = string.Empty;
if (input == string.Empty)
return HQL; string[] sArray = input.Split(',');
foreach (string str in sArray)
{
if (str.Length == ) continue;
HQL += "'" + str + "',";
}
if (HQL.Substring(HQL.Length - , ) == ",")
HQL = HQL.Substring(, HQL.Length - );
return HQL; } /// <summary>
/// 把字符串以逗号分格,转换成数据库格式''a'',''b''
/// </summary>
public static string ToSQLInDataFormatTwo(string input)
{
string HQL = string.Empty;
if (input == string.Empty)
return HQL; string[] sArray = input.Split(',');
foreach (string str in sArray)
{
if (str.Length == ) continue;
HQL += "''" + str + "'',";
}
if (HQL.Substring(HQL.Length - , ) == ",")
HQL = HQL.Substring(, HQL.Length - );
return HQL;
} public static string ToSQLInDataFormat(string[] input)
{
string HQL = string.Empty;
if (input.Length == )
return HQL; foreach (string str in input)
{
HQL += "'" + str + "',";
}
if (HQL.Substring(HQL.Length - , ) == ",")
HQL = HQL.Substring(, HQL.Length - );
return HQL; } /// <summary>
/// 从table转成dataset
/// </summary>
/// <param name="dt"></param>
/// <returns></returns>
public static DataSet TableToDataSet(DataTable dt)
{
DataSet ds = new DataSet();
ds.Tables.Add(dt);
return ds;
} public static DataSet TableToDataSet(DataTable[] dtArr)
{
DataSet ds = new DataSet();
for (int i = ; i < dtArr.Length; i++)
{
ds.Tables.Add(dtArr[i]);
}
return ds;
} /// <summary>
/// 修改对表的某列的值
/// </summary>
/// <param name="dt"></param>
/// <param name="value"></param>
public static bool UpdateTableCol(DataTable dt, string fieldName, object value)
{
try
{
if (dt.Columns.IndexOf(fieldName) < )
throw new Exception("表没有" + fieldName + "列!"); foreach (DataRow dr in dt.Rows)
{
dr[fieldName] = value;
} return true;
}
catch
{
return false;
} } /// <summary>
/// 以逗号分格字符串,返回数组
/// 如果第一个和最后一个字符为, 去掉
/// </summary>
/// <param name="str"></param>
/// <returns></returns>
public static string[] ToStringSplit(string str)
{
if (str.Length > )
{
if (str[] == ',')
str = str.Substring(, str.Length - );
if (str[str.Length - ] == ',')
str = str.Substring(, str.Length - );
}
string[] sArray = str.Split(',');
return sArray;
} /// <summary>
/// 把一个行的数据新增一个表中
/// </summary>
/// <param name="dt"></param>
/// <param name="dr"></param>
/// <returns></returns>
public static DataTable AddTableRowByRow(DataTable dt, DataRow dr)
{ bool b = false;
DataRow drNew = dt.NewRow();
for (int i = ; i < dr.Table.Columns.Count; i++)
{
string colname = dr.Table.Columns[i].ColumnName;
if (dt.Columns.IndexOf(colname) >= )
{
drNew[colname] = dr[colname];
b = true;
}
} if (b)
dt.Rows.Add(drNew);
return dt;
} } /// <summary>
/// 对字符或字符串的处理
/// </summary>
public class DOString
{
/// <summary>
/// 把字符转成大写并去两边空格
/// </summary>
public static string ToTrimAndUpper(string str)
{
return str.Trim().ToUpper();
} public static string ToTrimAndUpper(object o)
{
return o.ToString().Trim().ToUpper();
} public static string ToTrimAndBigToSmall(object o)
{
return BigToSmall(o.ToString().Trim(), );
} /// <summary>
/// 返回一个半角 去左右空格 大写的字符串
/// </summary>
public static string ToTUBS(object o)
{
return BigToSmall(o.ToString().Trim().ToUpper(), );
} /// <summary>
/// 判断字符是否是数字。是返回true
/// </summary>
/// <param name="c"></param>
/// <returns></returns>
public static bool NuNumber(char c)
{
if ((int)c >= && (int)c <= )
return true;
else
return false; } /// <summary>
/// 去除千分号
/// </summary>
public static object OffkiloSign(object obj)
{
if (obj == null)
return obj;
string s = obj.ToString();
return s.Replace(",", string.Empty);
} /// <summary>
/// 全角半角间转换 direction =-1 (半角转全角)
/// </summary> public static string BigToSmall(string content, int direction)
{
string strBig, to_strBig;
strBig = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789 '﹃﹄『』$/abcdefghijklmnopqrstuvwxyz.*";
to_strBig = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789 '“”“”$/abcdefghijklmnopqrstuvwxyz.*";
int i;
for (i = ; i < strBig.Length; i++)
{
if (direction != -)
{
content = content.Replace(strBig[i], to_strBig[i]);
}
else
{
content = content.Replace(to_strBig[i], strBig[i]);
}
}
return content;
} /// <summary>
/// 对比两个字符串的ASCII值大小,要是X1>X2,将X1,X2交换
/// </summary>
public static void CompareStringASCII(ref string x1, ref string x2)
{
if (string.IsNullOrEmpty(x1) || string.IsNullOrEmpty(x2))
return;
string y1 = x1.ToUpper();
string y2 = x2.ToUpper();
int iLength = y1.Length;
if (y2.Length < iLength)
iLength = y2.Length;
for (int i = ; i < iLength; i++)
{
int iASC1 = (int)y1[i];
int iASC2 = (int)y2[i];
if (iASC1 > iASC2)
{
string tmp = x1;
x1 = x2;
x2 = tmp;
break;
} if (iASC1 < iASC2)
break; }
} /// <summary>
/// 查找出text中含有spilt字符串从第几个字符结束的位置数组
/// </summary>
/// <param name="text">"12345678901234567890"</param>
/// <param name="spilt">"12"</param>
/// <returns>2,13</returns>
public static int[] DoStringIndexArray(string text, string spilt)
{
int[] ret = null;
try
{
int iStart = ;
int iEnd = text.Length - ;
int spiltLength = spilt.Length;
ArrayList list = new ArrayList();
while (iStart <= iEnd)
{
int index = text.IndexOf(spilt, iStart);
iStart = index + spiltLength;
if (iStart <= iEnd)
{
list.Add(iStart);
}
}
ret = new int[list.Count];
for (int i = ; i < ret.Length; i++)
{
ret[i] = Convert.ToInt32(list[i]);
}
}
catch
{
ret = null;
}
return ret;
} } }

对象列表转换为DataTable或DataTable转换为对象列表.的更多相关文章

  1. Asp.net 将DataTable 或者DataSet 转换为Json 格式

    Web 开发中,将从数据库中取到的数据直接转换为 Json 格式的数据,在前台通过Ajax 无刷新显示在界面上,下面提供将DataTable 或者DataSet 转换为Json 的方法 /// < ...

  2. 将list<对象>转换成DataTable,把DataTable转换成参数传入存储过程实现批量插入数据

    领导让在存储过程中批量添加数据,找出效率最高的,我看到后台代码后,发现可以将list<对象>转换成DataTable,把DataTable转换成参数传入存储过程实现批量插入数据,知道还有其 ...

  3. 简单的反射 把datatable 转换成list对象

    /// <summary> /// 把datatable 转换成list对象 /// </summary> /// <typeparam name="T&quo ...

  4. RestTemplate将响应数据转换为具有泛型的类对象

    前言: 重要,RestTemplate在SpringBoot项目里即便通过HttpMessageConverters添加了Fastjson且优先级比jackson要高也不会在RestTemplate里 ...

  5. DataTable转任意类型对象List数组-----工具通用类(利用反射和泛型)

    public class ConvertHelper<T> where T : new() { /// <summary> /// 利用反射和泛型 /// </summa ...

  6. jquery实现点击展开列表同时隐藏其他列表 js 对象操作 对象原型操作 把一个对象A赋值给另一个对象B 并且对象B 修改 不会影响 A对象

    这篇文章主要介绍了jquery实现点击展开列表同时隐藏其他列表的方法,涉及jquery鼠标事件及节点的遍历与属性操作技巧,具有一定参考借鉴价值,需要的朋友可以参考下 本文实例讲述了jquery实现点击 ...

  7. 反射List<M> To DataTable|反射IList To DataTable|反射 DataTable To List<M>

    将DataTable集合反射获取 List<M> /// <summary> /// 根据DataTable集合反射获取 List<M> /// </summ ...

  8. [翻译] 编写高性能 .NET 代码--第二章 GC -- 减少分配率, 最重要的规则,缩短对象的生命周期,减少对象层次的深度,减少对象之间的引用,避免钉住对象(Pinning)

    减少分配率 这个几乎不用解释,减少了内存的使用量,自然就减少GC回收时的压力,同时降低了内存碎片与CPU的使用量.你可以用一些方法来达到这一目的,但它可能会与其它设计相冲突. 你需要在设计对象时仔细检 ...

  9. js对象系列【一】深层理解对象与原型

    我们先从盘古开天辟地时捋一捋对象: 从宏观内容来讲,javascript是一个属性的集合,包括值,函数,而整个集合也可以类比为一个对象. js = { a的变量名: a的值, ... 函数b: fun ...

随机推荐

  1. ISAP算法对 Dinic算法的改进

    ISAP算法对 Dinic算法的改进: 在刘汝佳图论的开头引言里面,就指出了,算法的本身细节优化,是比较复杂的,这些高质量的图论算法是无数优秀算法设计师的智慧结晶. 如果一时半会理解不清楚,也是正常的 ...

  2. c# wpf定时器的一种用法

    1.xaml页面 <Window x:Class="EssentialWPF.MainWindow" xmlns="http://schemas.microsoft ...

  3. 使用 Python 切割图片

    刚好我有张 PNG 图片需要均匀切割,刚好我不会 PhotoShop,刚好我想用 Python 来练练手. 于是撸袖子码脚本. import os from PIL import Image def ...

  4. 调用discuz编辑器发布帖子显示html代码的解决办法

    <!--{echo htmlspecialchars_decode(discuzcode($post[message], , , , , , , , , , ));}--> 在discuz ...

  5. linux下用用iptables做端口映射的shell

    情形一:跨网络.跨主机的映射Full-Nat 我们想到达主机B的80端口,但是由于网络限制可能无法直接完成.但是我们可以到达主机A的8080端口,而主机A可以直接到达B的80端口.这时候可以使用ipt ...

  6. C++ 中注意,零扩展和符号位扩展

    版权声明:本文为博主原创文章,未经博主允许不得转载. 首先,介绍一下两种扩展的定义 转 http://blog.csdn.net/jaylong35/article/details/6160736 符 ...

  7. '"千"第一周学习情况记录

    一周过去了,今天将我这一周的学习内容和主要感想记录与此和大家共同分享,一起进步.我将自己的学习计划命名为"千",因为我喜欢这个字,希望能用此来鼓舞自己不断前进.时间总是很快的,这一 ...

  8. Analyzer报表里显示的 * 星号、红叉、#井号的意义

    声明:原创作品,转载时请注明文章来自SAP师太技术博客( 博/客/园www.cnblogs.com):www.cnblogs.com/jiangzhengjun,并以超链接形式标明文章原始出处,否则将 ...

  9. JAX-WS使用Handler Chain加工消息

    承前 本文的示例,是基于前一篇文章中的实例而改进的,如果想要运行本文的代码例子,需要先实现前一篇的代码. 前一篇文章JAX-WS开发WebService初级 Handler概念 在WebService ...

  10. dubbo & zookeeper & springMVC

    一.安装准备 1.环境简介 名称 版本 OS Mac OS X 10.11.5 JDK 1.8.0_51 dubbo 2.5.4 tomcat 8.0.35 Zookeeper 3.4.8 maven ...