当前位置:网站首页>【C# - 方法封装】数据转换
【C# - 方法封装】数据转换
2022-08-04 05:35:00 【小呆瓜耶】
目录
一、DataTable & List 相互转换
1.DataTable 转换为 List
using System.Data;
using System.Reflection;
/// <summary>
/// DataTable转换为List<T>对象
/// </summary>
/// <param name="dataTable">DataTable 对象</param>
/// <returns>List<T>集合</returns>
public static List<T> DataTableToList<T>(DataTable dataTable) where T : class, new()
{
// 定义集合
List<T> ts = new List<T>();
//定义一个临时变量
string tempName = string.Empty;
//遍历DataTable中所有的数据行
foreach (DataRow dr in dataTable.Rows)
{
T t = new T();
// 获得此模型的公共属性
PropertyInfo[] propertys = t.GetType().GetProperties();
//遍历该对象的所有属性
foreach (System.Reflection.PropertyInfo pi in propertys)
{
tempName = pi.Name;//将属性名称赋值给临时变量
//检查DataTable是否包含此列(列名==对象的属性名)
if (dataTable.Columns.Contains(tempName))
{
//取值
object value = dr[tempName];
//如果非空,则赋给对象的属性
if (value != DBNull.Value)
{
pi.SetValue(t, value, null);
}
}
}
//对象添加到泛型集合中
ts.Add(t);
}
return ts;
}
2.List 转换为 DataTable
需要引用Newtonsoft.Json包
using Newtonsoft.Json;
using System.Data;
/// <summary>
/// List<T>转换为DataTable
/// </summary>
/// <param name="list">请求的list</param>
/// <returns></returns>
public static DataTable ListToDataTable<T>(List<T> list)
{
//创建一个空表
DataTable dt = new DataTable("tableName");
//创建传入对象名称的列
foreach (var item in list.FirstOrDefault().GetType().GetProperties())
{
dt.Columns.Add(item.Name);
}
//循环存储
foreach (var item in list)
{
//新加行
DataRow value = dt.NewRow();
//根据DataTable中的值,进行对应的赋值
foreach (DataColumn dtColumn in dt.Columns)
{
int i = dt.Columns.IndexOf(dtColumn);
//基元元素,直接复制,对象类型等,进行序列化
if (value.GetType().IsPrimitive)
{
value[i] = item.GetType().GetProperty(dtColumn.ColumnName).GetValue(item);
}
else
{
value[i] = JsonConvert.SerializeObject(item.GetType().GetProperty(dtColumn.ColumnName).GetValue(item));
}
}
dt.Rows.Add(value);
}
return dt;
}
二、DataTable & Json 相互转换
1.DataTable 转换为 Json字符串
需要引用Newtonsoft.Json包
using Newtonsoft.Json;
using System.Collections;
using System.Data;
/// <summary>
/// DataTable转换为Json字符串
/// </summary>
/// <param name="dataTable">DataTable 对象</param>
/// <returns>JSON字符串</returns>
public static string DataTableToJson(DataTable dataTable)
{
//定义ArrayList
ArrayList arrayList = new ArrayList();
//遍历DataTable中所有的数据行
foreach (DataRow dr in dataTable.Rows)
{
//定义字典【列名,值】
Dictionary<string, object> columnsDic = new Dictionary<string, object>();
//遍历DataTable中所有的数据列
foreach (DataColumn dc in dataTable.Columns)
{
//字典添加列名,值
columnsDic.Add(dc.ColumnName, dr[dc.ColumnName]);
}
//arrayList添加字典
arrayList.Add(columnsDic);
}
//序列化
return JsonConvert.SerializeObject(arrayList);
}
2.Json 转换为 DataTable
using System.Data;
using System.Text.RegularExpressions;
/// <summary>
/// Json转换为DataTable
/// </summary>
/// <param name="strJson">得到的json</param>
/// <returns></returns>
public static DataTable JsonToDataTable(string strJson)
{
//转换json格式
strJson = strJson.Replace(",\"", "*\"").Replace("\":", "\"#").ToString();
//取出表名
var rg = new Regex(@"(?<={)[^:]+(?=:\[)", RegexOptions.IgnoreCase);
string strName = rg.Match(strJson).Value;
DataTable tb = null;
//去除表名
strJson = strJson.Substring(strJson.IndexOf("[") + 1);
strJson = strJson.Substring(0, strJson.IndexOf("]"));
//获取数据
rg = new Regex(@"(?<={)[^}]+(?=})");
MatchCollection mc = rg.Matches(strJson);
for (int i = 0; i < mc.Count; i++)
{
string strRow = mc[i].Value;
string[] strRows = strRow.Split('*');
//创建表
if (tb == null)
{
tb = new DataTable();
tb.TableName = strName;
foreach (string str in strRows)
{
var dc = new DataColumn();
string[] strCell = str.Split('#');
if (strCell[0].Substring(0, 1) == "\"")
{
int a = strCell[0].Length;
dc.ColumnName = strCell[0].Substring(1, a - 2);
}
else
{
dc.ColumnName = strCell[0];
}
tb.Columns.Add(dc);
}
tb.AcceptChanges();
}
//增加内容
DataRow dr = tb.NewRow();
for (int r = 0; r < strRows.Length; r++)
{
dr[r] = strRows[r].Split('#')[1].Trim().Replace(",", ",").Replace(":", ":").Replace("\"", "");
}
tb.Rows.Add(dr);
tb.AcceptChanges();
}
return tb;
}
边栏推荐
- 目标检测中的IoU、GIoU、DIoU与CIoU
- 用chrome dev tools 强制js注入
- 给想要转行渗透测试人的忠告
- golang 坐标格式 转换 GCJ02ToWGS84
- Network skills: teach you to install batteries on the router, you can still surf the Internet when the power is cut off!
- ssm pom文件依赖 web.xml配置
- 数据库:整理四个实用的SQLServer脚本函数
- A semi-supervised Laplace skyhawk optimization depth nuclear extreme learning machine for classification
- SENet detailed explanation and Keras reproduction code
- 缓动动画,有关窗口的一些常见操作,BOM操作
猜你喜欢
Operating System Kernel
树莓派 4 B 拨动开关控制风扇 Rasberry Pi 4 B Add Toggle Switch for the Fan
Network skills: teach you to install batteries on the router, you can still surf the Internet when the power is cut off!
LeetCode刷题
Interpretation of EfficientNet: Composite scaling method of neural network (based on tf-Kersa reproduction code)
Online public account article content to audio file practical gadget
MySQL之SQL结构化查询语言
数据库知识:SQLServer创建非sa用户笔记
IoU, GIoU, DIoU and CIoU in target detection
杰哥带大家做一次meterpreter内网渗透模拟
随机推荐
Stream API
Flask request 返回网页中 checkbox 是否选中
关于gopher协议的ssrf攻击
网络技巧:教你给路由器装上电池,断电照样可以上网!
子空间结构保持的多层极限学习机自编码器(ML-SELM-AE)
Memory limit should be smaller than already set memoryswap limit, update the memoryswap at the same
MAML原理讲解和代码实现
冰歇webshell初探
Time Series Forecasting Based on Reptile Search RSA Optimized LSTM
Uos统信系统 chrony配置
GRNN、RBF、PNN、KELM之间究竟有什么联系?
树莓派 4 B 拨动开关控制风扇 Rasberry Pi 4 B Add Toggle Switch for the Fan
注册表设置默认浏览器 win7,winserver 2008,winserver 2012
数据库知识:SQLServer创建非sa用户笔记
罗斯50分
DenseNet详解及Keras复现代码
JUC锁框架——CountDownLatch、CyclicBarrier和Semaphore
IE8 打开速度慢的解决办法
一场聚会,转行渗透测试月薪13.5k,感谢那个女同学......
20170729