利用扩展方法将DataTable转换为特定类型的对象数组

EPANET水力引擎详解:Hazen-Williams公式怎么选?水泵与阀门模拟实操避坑指南 本文深入解析EPANET水力引擎的核心机制,包括Hazen-Williams公式的适用场景、水泵与阀门的模拟实操技巧,以及求解器崩溃的解决方案。通过工业循环水系统和高层建筑供水等案例,帮助工程师规避常见建模陷阱,提升模型精度与工程决策可靠性。 阅读详情
在ADO.NET中,从数据库中获得的数据可以保存在DataTable中,当然这个DataTable可以是强类型的。但是很多时候,我们都是用弱类型的DataTable, 那么有没有一个简单的方法可以把一个DataTable转换为一个特定类型的对象数组?
其实在LINQ To SQL中,用了一些attribute来辅助.net将一个数据库中的table转换为一个Object,这些attribute位于System.Data.Linq.Mapping namespace下,主要是TableAttribute和ColumnAttribute。

假设数据库中有一个user的table,那么我们可以定义一个User的class:

  1.     public class User
  2.     {
  3.         private int id;
  4.         private string name;

  5.         [Column(Name="id")]
  6.         public int ID
  7.         {
  8.             get
  9.             {
  10.                 return this.id;
  11.             }
  12.             set
  13.             {
  14.                 this.id = value;
  15.             }
  16.         }
  17.         [Column(Name = "name")]
  18.         public string Name
  19.         {
  20.             get
  21.             {
  22.                 return this.name;
  23.             }
  24.             set
  25.             {
  26.                 this.name = value;
  27.             }
  28.         }
  29.     }
我们用Column Attribute来标识User的属性在user Table中对应的列名。然后,我们可以为DataTable提供一个扩展方法来将DataTable转换为一个数组:
  1. public static T[] ToObject<T>(this DataTable dataTable)
  2.     where T:new()
  3. {           
  4.     List<T> list=new List<T>();
  5.     foreach(DataRow row in dataTable.Rows)
  6.     {
  7.         T t = new T();
  8.         Type type = t.GetType();
  9.         PropertyInfo[] propertyInfos =type.GetProperties();
  10.         if (propertyInfos != null && propertyInfos.Length > 0)
  11.         {
  12.             foreach (PropertyInfo info in propertyInfos)
  13.             {
  14.                 object[] columns =info.GetCustomAttributes(typeof(ColumnAttribute),true);
  15.                 if (columns != null && columns.Length == 1)
  16.                 {
  17.                     ColumnAttribute ca = columns[0] as ColumnAttribute;
  18.                     string name = ca.Name;
  19.                     if (name == null || name.Length == 0)
  20.                     {
  21.                         name = info.Name;
  22.                     }
  23.                     object propertyValue = row[name];
  24.                     if (propertyValue == DBNull.Value)
  25.                     {
  26.                         propertyValue = null;
  27.                     }
  28.                     info.SetValue(t, propertyValue, null);
  29.                 }
  30.             }
  31.         }
  32.         list.Add(t);
  33.     }
  34.     return list.ToArray();;
  35. }
最后,提供一下如何使用该方法来从数据库中获取user列表(使用MySQL数据库);

  1. using (MySqlConnection connection = new MySqlConnection(this.connectionString))
  2. {
  3.     connection.Open();
  4.     MySqlDataAdapter dataAdapter = new MySqlDataAdapter("select * from user", connection);     
  5.     DataTable dt = new DataTable();
  6.     dataAdapter.Fill(dt);
  7.    User[] users=dt.ToObject<User>();
  8.    //Now we get the user list...
  9. }
当然,DataTable的扩展方法还远没有完善,应该还需要考虑类型转换之类的问题。更进一步的改进可能是利用工具来自动生成User class,这样就能省下一定的工作量。
C#.net开发 List与DataTable相互转换 在.NET开发中,操作关系型数据库提取数据经常用到DataTable。ASP.NET前后台数据绑定应用DataTable的时候似乎也很多,但是List集合比DataTable应用更加广泛,提取处理数据也更加方便,MVC绑定数据更倾向于List。 因此,我们会经常需要对List集合和DataTable数据进行互转,以下三个方法是实现List和DataTable互转,以及DataTable单行提取对象 阅读详情

相关推荐

Datatable转实体数组

Datatable转实体数组,人民币转换、重量转换、 转大写、数据集合转换,将数字转化为大写

把一个DataTable对象转换成一个数组对象

示例代码1:(DataTable中包含多列数据的情况)         public Customer[] GetAll()         {             DataTable table = SqlHelper.ExecuteDataTable("select FId, FName, FBirthday, FCustLevel, FTelNum ,FAddress

zunguitiancheng的专栏 5080

c#扩展datatable转json示例

代码如下:namespace PadWebServices.Model{   public static class DataTableExtender    {       public static string ToJson(this DataTable dt,string tbName)  // this DataTable 标识对DataTable类的扩展            {                StringBuilder JsonString = new StringBuilder();                if (dt != null && dt.Row

把DataTable自动转换出Object对象集

大家好,这是我第一次在CSDN上发表我的文章, 希望得到前辈们的支持和指点。言归正传,由于一个实例对象中包括的字段和属性很多,而每次在从数据库中取出对象时,写的类似如下的代码就会很多很多,我每次写这些代码的时候心情会很烦。int ID = int.Parse(dt.Rows[0]["id"].ToString());            string McOK = int.Parse(d

薛建峰与.Net 4219

ATAC-seq数据分析流程学习记录及总结

记录ATAC-seq数据分析流程,主要是参考健明老师的教程以及网上各种学习资源进行总结,网址在下面。

ACGTexplorer的博客 3764

手把手教你用Qwen-7B打造医疗大模型:从数据准备到RLHF全流程实战

本文是一篇基于Qwen-7B-Chat模型构建医疗领域大模型的实战全流程指南。文章详细拆解了从数据准备、环境搭建,到增量预训练、监督微调(SFT)以及偏好对齐(DPO)的核心技术步骤,并分享了部署与持续优化的实践经验。通过LoRA等高效微调技术,帮助开发者掌握将通用大模型改造为专业领域专家的完整方法论。

weixin_29191761的博客 132

C# DataTable转为对象或对象列表

需求:从DataTable中直接生成指定类的对象或对象列表 使用:datatable.ToListModel(); 代码: using System; using System.Collections.Generic; using System.Data; using System.Linq; using System.Web; /// /// DataTableToModel 的摘要说

apollokk的专栏 8913

手把手教你用SIMCOM A7670C_FASL模组实现双路MQTT连接阿里云(附完整源码)

本文详细介绍了如何使用SIMCOM A7670C_FASL 4G模组实现双路MQTT连接阿里云,包括硬件配置、开发环境搭建、双路MQTT架构设计及实现细节。通过完整的源码示例和实战指南,帮助开发者快速掌握物联网设备开发中的多路MQTT连接技术,提升工业级应用的开发效率。

weixin_33696822的博客 231

HOW TO:对象数组转换为表(DataTable)

HOW TO:对象数组转换为表(DataTable) Author:水如烟(http://blog.csdn.net/lzmtw)Date:2005-4-15 有时候我们想将数组的内容显示在DataGrid上。怎么做呢,MSDN关于DataGrid的说明上说,“也可以将 DataGrid 绑定到 ArrayList。ArrayList 的一个功能是它可以包含多种类型的对

水如烟 3217

信息学奥赛一本通高手训练1680:序列

题目 代码 #include<cstdio> #include<iostream> #include<cmath> #define LL long long using namespace std; const LL N = 1400000+7; const LL mod = 1e9+7; int n, t; LL pos[N], sum[N], ans[N]; struct node{ LL ll, rr; }a[N]; int main(){ p

qingfeixueyue的博客 473

数据分享|1961-2017年中国0.25°×0.25° 逐日地表水文数据集(VIC-CN05.1)

其中,全球径流中心(University of New Hampshire and Global Runoff Data Centre, UNH/GRDC)的复合产流场集成了观测的河道径流和水量平衡模式模拟的地表和地下径流,常被用来评估模拟的径流。在长白山、海北灌丛和千烟洲通量站,模拟与观测的逐月潜热通量的平均NSE为0.61。VIC-CN05.1受益于较准确的大气驱动场、先进的地表水文参数化方案以及更真实丰富的土壤信息,可作为中国水文气象研究的参照数据,用于陆面模式的评估和长期的趋势分析等。

J_Giser的博客 1844

C# DataTable和List之间相互转换

通过反射实现List和DataTable的转换,DataTable和Entity的转换

kusse的博客 1万+

Windows 下 OpenClaw(小龙虾) 安装全记录:从零到一的保姆级图文教程(持续更新中)

本文主要介绍了Windows 下 OpenClaw 安装全记录:从零到一的保姆级图文教程,希望能对学习使用OpenClaw 的同学们有所帮助。 文章目录 1. 背景 2. 实战教程 2.1 步骤一 安装Node.js 2.2 步骤二:安装并配置OpenClaw 2.3 步骤三:配置模型 2.4 步骤四:对话 3. 后续使用步骤

weixin_43178406的博客 16万+

C# 数组转换为DataTable 的三个方法

C# 数组转换为DataTable 的三个方法 view plaincopy to clipboardprint?using System;   using System.Data;     namespace ArrayToDataTable   {       class ArrayToDataTable       {           ///            /// 把一个

jiang0609的专栏 2254

智能车图像处理4-入门级分析3 ---十字路口补线

PS :入门级文章适合新手,如果已经有基础可以去看进阶篇文章。

taiyuezyh的博客 1万+

pscad IEEE标准系统搭建说明

pscad IEEE标准系统搭建说明,包含典型的IEEE 9节点、14节点、30节点、39节点和118节点系统。内含标准测试系统的原始数据和潮流结果。

将IEnumerable<T>类型的集合转换为DataTable类型

作者:李仁海 撰写时间:2019.5.28 一、将IEnumerable类型的集合转换为DataTable类型 1、首先命一名的类型LINQToDataTable,这可以更好的使用他的作用,传递的数值IEnumerable的类型集合来进行转换为DataTable类型的模式还有,他是一个公开枚举数,该枚举数支持在指定类型的集合上进行简单 代;还有varlist的参数值的传递。 (1)那么接着就是定义...

weixin_44542146的博客 1678

复分析 阿尔福斯(Ahlfors) 第三版答案 英文

答案分为十章,有部分习题没有答案,全英文复分析阿尔福斯(Ahlfors) 第三版答案

DataTable与数组相互转换

DataTable与数组相互转换

qq_44947841的博客 2729

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

数学建模模型总结

这是本人在两年内准备参加数学建模竞赛搜集到的模型资料,已经经过了本人的筛选和整理,希望能够对准备参加数学建模竞赛的学弟学妹们提供一些帮助!

将DataTable对象转换为Recordset对象(C#)

将DataTable对象转换为Recordset对象在.net中用ADO.NET取代了ADO实现对数据的访问,但一些COM控件只支持ADO并不支持ADO.NET。为了使用这类控件,只能将ADO.NET中的数据对象,比如DataTable为ADO中的Recordset(DataSet对象本质上是DataTable的集合,因此本文只讲述DataTable对象的转换)。思路1.         创建

shaily读书学习 2540

对象数组转换为DataTable的方法

在我们的项目中,用到了很多对象数组。需要把对象数组绑定到DataGrid上,但目前好像不能直接绑定。就只有转换为DataTable。好不容易在网上找到了别人写的一个类。但和我们的需要比还是差了一点。他只能把对象的属性转换为DataTable的列。但我们的对象数组都是WebServices自动生成的。也就是没有属性,只有Public的字段。所以我就在别人的基础上写了一个即可以转换属性又可以转换字段的

君无忌的专栏 2249

C#语言中对象数组到DataTable的转换

今天在开发工作中遇到了一个问题: 我的很多DataGridView,因为数据源(DataSource)使用的是数组,导致在点击每列列头的时候无法就指定列进行排序 因此我需要写一个将数组转换为DataTable的函数。 在网上查了一下,找到了这篇Blog,总结得比较全面: http://...

1438

DataTable 和字符串数组之间进行转换

using System;using System.Data;using System.Configuration;using System.Web;using System.Web.Security;using System.Web.UI;using System.Web.UI.WebControls;using System.Web.UI.WebControls.W

nailwl 8258

隐含类型var 转换为 DataTable

using System;using System.Collections.Generic;using System.Linq;using System.Web;using System.Data;using System.ComponentModel;namespace SmartERP.Until{    public static  class CovertClass    {     

dtlcq的专栏 2542

将IEnumerable<T>类型的集合 转换为DataTable类型

将IEnumerable类型的集合 转换为DataTable类型 用Public创建一个头部 定义一个要返回的DataTable对象 保存列集合的属性信息数组 然后给他一个IF的循环遍历集合,使用反射获取类型的属性信息 然后用Foreach表示出他的参数 使用反射获取T类型的属性信息,返回一个PropertyInfo类型的集合 再用Foreach循环一个PropertyInfo数组 ...

weixin_44540482的博客 567

C# DataTable转换为JSON数组

C# DataTable转换为JSON public string DataTableToJson(DataTable table) { var JsonString = new StringBuilder(); if (table.Rows.Count > 0) { ...

weixin_41924879的博客 1244

将相同类型的数组转换为DataTable

c#二维数组转DataTable将具有相同类型的数组转换为DataTable 将具有相同类型的数组转换为DataTable 在开发过程中,经常会遇到将一个相同类型的数组转换为DataTable。DataTable主要是由行和列组成,那我们数组中类的属性其实就是Columns的名字: 首先将类的属性转换为PropertyInfo类型的数组 private PropertyInfo[] GetPropertyInfoArray() { PropertyInfo[] props = null;

weixin_46239451的博客 476
上一篇: 利用XmlSerializer来进行对象clone
foba
博客等级 码龄23年 0粉丝 7原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值