1、首先做个实体类
Entity.cs
Code
using System;
using System.Collections.Generic;
using System.Text;
namespace ConsoleApplication1
{
class Entity
{
private string _a;
private string _b;
private string _c;
public string a
{
get { return _a; }
set { _a = value; }
}
public string b
{
get { return _b; }
set { _b = value; }
}
public string c
{
get { return _c; }
set { _c = value; }
}
}
}
using System;
using System.Collections.Generic;
using System.Text;
namespace ConsoleApplication1
{
class Entity
{
private string _a;
private string _b;
private string _c;
public string a
{
get { return _a; }
set { _a = value; }
}
public string b
{
get { return _b; }
set { _b = value; }
}
public string c
{
get { return _c; }
set { _c = value; }
}
}
}
2、进行赋值
Program.cs
Code
using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using System.Reflection;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
DataSet ds = new DataSet();
DataTable dt = new DataTable();
dt.Columns.Add("a", typeof(string));
dt.Columns.Add("b", typeof(string));
dt.Columns.Add("c",typeof(string));
DataRow dr = dt.NewRow();
dr["a"] = "aa";
dr["b"] = "bb";
dr["c"] = "cc";
dt.Rows.Add(dr);
ds.Tables.Add(dt);
Entity entity = new Entity();
foreach (DataRow row1 in ds.Tables[0].Rows)
{
foreach (DataColumn col in row1.Table.Columns)
{
PropertyInfo pi = typeof(Entity).GetProperty(col.ColumnName);
pi.SetValue(entity, ds.Tables[0].Rows[0][col.ColumnName].ToString(), null);
}
}
System.Console.WriteLine(entity.a);
System.Console.WriteLine(entity.b);
System.Console.WriteLine(entity.c);
}
}
}
using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using System.Reflection;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
DataSet ds = new DataSet();
DataTable dt = new DataTable();
dt.Columns.Add("a", typeof(string));
dt.Columns.Add("b", typeof(string));
dt.Columns.Add("c",typeof(string));
DataRow dr = dt.NewRow();
dr["a"] = "aa";
dr["b"] = "bb";
dr["c"] = "cc";
dt.Rows.Add(dr);
ds.Tables.Add(dt);
Entity entity = new Entity();
foreach (DataRow row1 in ds.Tables[0].Rows)
{
foreach (DataColumn col in row1.Table.Columns)
{
PropertyInfo pi = typeof(Entity).GetProperty(col.ColumnName);
pi.SetValue(entity, ds.Tables[0].Rows[0][col.ColumnName].ToString(), null);
}
}
System.Console.WriteLine(entity.a);
System.Console.WriteLine(entity.b);
System.Console.WriteLine(entity.c);
}
}
}