将数据表转换为动态实体 [英] converting data table into dynamic entity
本文介绍了将数据表转换为动态实体的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
namespace sample
{
class Patient
{
int Dosage { get; set; }
string Drug { get; set; }
string Patient1 { get; set; }
DateTime Date { get; set; }
List<Patient> _list = new List<Patient>();
public void GetData(DataTable Data)
{
foreach (DataRow row in Data.Rows)
{
Patient p = new Patient();
p.Load(row.ItemArray);
_list.Add(p);
}
}
private void Load(object[] p)
{
this.Dosage=(int)p[0];
this.Drug = p[1].ToString();
this.Patient1 = p[2].ToString();
this.Date = (DateTime)p[3];
}
}
}
namesapce sample
{
pulic class program
{
public void main()
{
Patient p = new Patient();
DataTable table = GetTable();
p.GetData(table);
}
static DataTable GetTable()
{
DataTable table = new DataTable();
table.Columns.Add("Dosage", typeof(int));
table.Columns.Add("Drug", typeof(string));
table.Columns.Add("Patient", typeof(string));
table.Columns.Add("Date", typeof(DateTime));
table.Rows.Add(25, "Indocin", "David", DateTime.Now);
table.Rows.Add(50, "Enebrel", "Sam", DateTime.Now);
table.Rows.Add(10, "Hydralazine", "Christoff", DateTime.Now);
table.Rows.Add(21, "Combivent", "Janet", DateTime.Now);
table.Rows.Add(100, "Dilantin", "Melanie", DateTime.Now);
return table;
}
}
}
这是我的类和数据结构,现在我需要如何将该数据表转换为动态实体,如果您知道有人请帮忙,我得到了一些链接,但我不明白,因此任何人都可以看到此链接,请给我解决方案请
http://www.codeproject.com/script/Articles/ArticleVersion.aspx?aid=157601&av=232018
this is the my class and data structure now i need how i can this data table into dynamic entities and if u know anyone please help and i got some link but i did''t understood so any one see this link and please give me solution please
http://www.codeproject.com/script/Articles/ArticleVersion.aspx?aid=157601&av=232018
推荐答案
尝试这样做,这样就可以了
首先,我要创建一种提取方法
Try like that and iy should work
First I am creating a Extiontion method
public static class MyExtensionClass
{
public static List<t> ToCollection<t>(this DataTable dt)
{
List<t> lst = new System.Collections.Generic.List<t>();
Type tClass = typeof(T);
PropertyInfo[] pClass = tClass.GetProperties();
List<datacolumn> dc = dt.Columns.Cast<datacolumn>().ToList();
T cn;
foreach (DataRow item in dt.Rows)
{
cn = (T)Activator.CreateInstance(tClass);
foreach (PropertyInfo pc in pClass)
{
try
{
DataColumn d = dc.Find(c => c.ColumnName == pc.Name);
if (d != null)
pc.SetValue(cn, item[pc.Name], null);
}
catch
{
}
}
lst.Add(cn);
}
return lst;
}
}
</datacolumn></datacolumn></t></t></t></t>
现在您可以像这样调用此方法
Now you can call this method like that
DataTable dt = getTable();
List<patient> lst = GetTable().ToCollection<patient>();
foreach (Patient cn in lst)
{
Response.Write(cn.ToString() + "<br />");
}
</patient></patient>
这篇关于将数据表转换为动态实体的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文