DataConvert

using Newtonsoft.Json.Linq;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Reflection;
using System.Web.Script.Serialization;

namespace MES
{
/// <summary>
/// 数据转换通用类
/// </summary>
public class DataConvert
{
/// <summary>
/// List泛型转DataTable
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="collection"></param>
/// <returns></returns>
public static DataTable ListToDataTable<T>(IEnumerable<T> collection)
{
var props = typeof(T).GetProperties();
var dt = new DataTable();

foreach (var prop in props)
{
Type type = prop.PropertyType;

//Nullable处理
if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Nullable<>))
{
type = Nullable.GetUnderlyingType(type);
}

dt.Columns.Add(prop.Name, type);
}
//dt.Columns.AddRange(props.Select(p =>
// new DataColumn(p.Name, p.PropertyType)).ToArray()
//);
if (collection.Count() > 0)
{
for (int i = 0; i < collection.Count(); i++)
{
ArrayList tempList = new ArrayList();
foreach (PropertyInfo pi in props)
{
object obj = pi.GetValue(collection.ElementAt(i), null);
tempList.Add(obj);
}
object[] array = tempList.ToArray();
dt.LoadDataRow(array, true);
}
}
return dt;
}

/// <summary>
/// DataTable转泛型
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="dt"></param>
/// <returns></returns>
public static List<T> ConvertTableToClass<T>(DataTable dt)
{
List<T> tlist = new List<T>();
if (dt.Rows.Count > 0)
{
System.Type t = typeof(T);
Assembly ass = Assembly.GetAssembly(t);//获取泛型的程序集
                PropertyInfo[] pc = t.GetProperties();//获取到泛型所有属性的集合
                foreach (DataRow dr in dt.Rows)
{
Object _obj = ass.CreateInstance(t.FullName);//泛型实例化
foreach (PropertyInfo pi in pc)
{
try
{
if (dr.Table.Columns.Contains(pi.Name))
{
if (pi.PropertyType.FullName.Contains("Int64"))//判断属性的类型是不是Int64
{
String _name = pi.Name;
pi.SetValue((T)_obj, dr[_name].Equals(DBNull.Value) ? (long)0 : Convert.ToInt64(dr[_name]), null);//给泛型的属性赋值
}
else if (pi.PropertyType.FullName.Contains("Int32"))//判断属性的类型是不是Int32
{
String _name = pi.Name;
pi.SetValue((T)_obj, dr[_name].Equals(DBNull.Value) ? 0 : Convert.ToInt32(dr[_name]), null);//给泛型的属性赋值
}
else if (pi.PropertyType.FullName.Contains("Int16"))//判断属性的类型是不是Int16
{
String _name = pi.Name;
//pi.SetValue((T)_obj, dr[_name].Equals(DBNull.Value) ? 0 : Convert.ToInt16(dr[_name]), null);//给泛型的属性赋值
if (dr[_name].Equals(DBNull.Value))
{
pi.SetValue((T)_obj, 0, null);
}
else
{
pi.SetValue((T)_obj, Convert.ToInt16(dr[_name]), null);
}
}
else if (pi.PropertyType.FullName.Contains("Decimal"))//判断属性的类型是不是Decimal
{
String _name = pi.Name;
if (!dr[_name].Equals(DBNull.Value))
{
pi.SetValue((T)_obj, Convert.ToDecimal(dr[_name]), null);//给泛型的属性赋值
}
}
else
{
String _name = pi.Name;
if (!dr[_name].Equals(DBNull.Value))
{
pi.SetValue((T)_obj, dr[_name], null);//给泛型的属性赋值
}
}
}
}
catch (Exception ex)
{
System.Console.WriteLine(ex.StackTrace);
}
}
tlist.Add((T)_obj);
}
}
return tlist;
}

/// <summary>
/// 16进制字符串转10进制
/// </summary>
/// <param name="hex">16进制</param>
/// <returns>10进制字符串</returns>
public static string Hex2Ten(string hex)
{
int num = 0;
int i = 0;
int num2 = hex.Length - 1;
while (i < hex.Length)
{
num += DataConvert.HexChar2Value(hex.Substring(i, 1)) * (int)Math.Pow(16.0, (double)num2);
num2--;
i++;
}
return Math.Abs(num).ToString();
}

static Dictionary<string, int> d1 = new Dictionary<string, int>(22);
/// <summary>
/// 16进制字符转10进制
/// </summary>
/// <param name="hexChar">16进制字符</param>
/// <returns>10进制数字</returns>
public static int HexChar2Value(string hexChar)
{
if (hexChar != null)
{
if (d1 == null)
{
Dictionary<string, int> dictionary = new Dictionary<string, int>(22);
dictionary.Add("0", 0);
dictionary.Add("1", 1);
dictionary.Add("2", 2);
dictionary.Add("3", 3);
dictionary.Add("4", 4);
dictionary.Add("5", 5);
dictionary.Add("6", 6);
dictionary.Add("7", 7);
dictionary.Add("8", 8);
dictionary.Add("9", 9);
dictionary.Add("a", 10);
dictionary.Add("A", 11);
dictionary.Add("b", 12);
dictionary.Add("B", 13);
dictionary.Add("c", 14);
dictionary.Add("C", 15);
dictionary.Add("d", 16);
dictionary.Add("D", 17);
dictionary.Add("e", 18);
dictionary.Add("E", 19);
dictionary.Add("f", 20);
dictionary.Add("F", 21);
d1 = dictionary;
}
int num;
if (d1.TryGetValue(hexChar, out num))
{
switch (num)
{
case 0:
case 1:
case 2:
case 3:
case 4:
case 5:
case 6:
case 7:
case 8:
case 9:
return Convert.ToInt32(hexChar);
case 10:
case 11:
return 10;
case 12:
case 13:
return 11;
case 14:
case 15:
return 12;
case 16:
case 17:
return 13;
case 18:
case 19:
return 14;
case 20:
case 21:
return 15;
}
}
}
return 0;
}
public static string TransStr(string ReStr)
{
if (ReStr.IndexOf(",") >= 0)
{
ReStr = ReStr.Replace(",", "/!");
}
string result;
if (ReStr.IndexOf(":") >= 0)
{
ReStr = ReStr.Replace(":", "/@");
result = ReStr;
}
else if (ReStr.IndexOf(";") >= 0)
{
ReStr = ReStr.Replace(";", "/#");
result = ReStr;
}
else if (ReStr.IndexOf("/") >= 0)
{
ReStr = ReStr.Replace("/", "//");
result = ReStr;
}
else
{
result = ReStr;
}
return result;
}
public static string RestoreStr(string ReStr)
{
if (ReStr.IndexOf("/!") >= 0)
{
ReStr = ReStr.Replace("/!", ",");
}
string result;
if (ReStr.IndexOf("/@") >= 0)
{
ReStr = ReStr.Replace("/@", ":");
result = ReStr;
}
else if (ReStr.IndexOf("/#") >= 0)
{
ReStr = ReStr.Replace("/#", ";");
result = ReStr;
}
else if (ReStr.IndexOf("//") >= 0)
{
ReStr = ReStr.Replace("//", "/");
result = ReStr;
}
else
{
result = ReStr;
}
return result;
}
public static bool IsDecimal(string str)
{
if (str.Length != 10) return false;
if (str == "")
return false;
const string PATTERN = @"[0-9]+$";
bool sign = false;
for (int i = 0; i < str.Length; i++)
{
sign = System.Text.RegularExpressions.Regex.IsMatch(str[i].ToString(), PATTERN);
if (!sign)
{
return sign;
}
}
return sign;
}

/// <summary>
/// Json数组转DataTable
/// </summary>
/// <param name="data"></param>
/// <returns></returns>
public static DataTable ArrayToDataTable(JArray data)
{
DataTable dt = new DataTable();
JObject job = (JObject)data[0];
foreach (var v in job)
{
dt.Columns.Add(v.Key);
}
for (int i = 0; i < data.Count; i++)
{
JObject data1 = (JObject)data[i];
DataRow dr = dt.NewRow();
foreach (var v in data1)
{
dr[v.Key] = (v.Value.ToString() == "" ? null : v.Value.ToString());
}
dt.Rows.Add(dr);
}

return dt;
}

/// <summary>
/// Json转Dictionary
/// </summary>
/// <param name="jsonData"></param>
/// <returns></returns>
/// <exception cref="Exception"></exception>
public static Dictionary<string, object> JsonToDictionary(string jsonData)
{
//实例化JavaScriptSerializer类的新实例
JavaScriptSerializer jss = new JavaScriptSerializer();
try
{
//将指定的 JSON 字符串转换为 Dictionary<string, object> 类型的对象
return jss.Deserialize<Dictionary<string, object>>(jsonData);
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}

/// <summary>
/// 将一个类型对象数据赋值到另一个类型对象(名字相同的情况)
/// </summary>
/// <typeparam name="T">目标类型</typeparam>
/// <param name="entity">目标类型对象</param>
/// <param name="dto">源对象</param>
/// <returns></returns>
public static object EntityDataEntity<T>(T entity, object dto) where T : class, new()
{
//if (dto == null || entity == null){return entity;}

//System.Reflection.PropertyInfo[] entityProperties = entity.GetType().GetProperties(System.Reflection.BindingFlags.Public);
//System.Reflection.PropertyInfo[] dtoProperties = dto.GetType().GetProperties(System.Reflection.BindingFlags.Public);

System.Reflection.PropertyInfo[] entityProperties = entity.GetType().GetProperties();
System.Reflection.PropertyInfo[] dtoProperties = dto.GetType().GetProperties();

if (entityProperties.Length <= 0) { return entity; }
if (dtoProperties.Length <= 0) { return entity; }

foreach (System.Reflection.PropertyInfo item in entityProperties)
{
foreach (var dtoItem in dtoProperties)
{
if (item.Name == dtoItem.Name)
{
if (item.PropertyType.IsValueType || item.PropertyType.Name.StartsWith("String"))
{
object value = dtoItem.GetValue(dto, null);
if (value != null)
item.SetValue(entity, value, null);
break;
}
else
{
object value = item.GetValue(entity, null);
object dtoValue = dtoItem.GetValue(dto, null);
value = EntityDataEntity(value, dtoValue);
if (value != null)
item.SetValue(entity, value, null);
break;
}
}
}
}
return entity;
}

public DataConvert()
{
}
}
}

posted @ 2026-01-29 09:55  chengeng  阅读(7)  评论(0)    收藏  举报