List<Model>对象转成DataTable

 C#方式

static class Program
{
/// <summary>
/// 应用程序的主入口点。
/// </summary>
[STAThread]
static void Main()
{
List<ModelList> list = new List<ModelList>();
list.Add(new ModelList { X = "小王0", Y = "40" });
list.Add(new ModelList { X = "小王1", Y = "50" });
list.Add(new ModelList { X = "小王2", Y = "60" });

DataTable dt = new DataTable("cart");
DataColumn dc1 = new DataColumn("tbl_name", Type.GetType("System.String"));
DataColumn dc2 = new DataColumn("tbl_Id", Type.GetType("System.String"));
dt.Columns.Add(dc1);
dt.Columns.Add(dc2);

foreach (ModelList ml in list)
{
    DataRow dr = dt.NewRow();
    dr["tbl_name"] = ml.X;
    dr["tbl_Id"] = ml.Y;
    dt.Rows.Add(dr);


}
public class ModelList
{
    public string X { get; set; }
    public string Y { get; set; }
}
}

 

VB方式


Shared Sub Main()
Dim list As List<ModelList> = New List<ModelList>()
list.Add(New ModelList
{
X = "小王0", Y = "40"
}
)
list.Add(New ModelList
{
X = "小王1", Y = "50"
}
)
list.Add(New ModelList
{
X = "小王2", Y = "60"
}
)

Dim dt As DataTable = New DataTable("cart")
Dim dc1 As DataColumn = New DataColumn("tbl_name",Type.GetType("System.String"))
Dim dc2 As DataColumn = New DataColumn("tbl_Id",Type.GetType("System.String"))
dt.Columns.Add(dc1)
dt.Columns.Add(dc2)

Dim ml As ModelList
For Each ml In list
Dim dr As DataRow = dt.NewRow()
dr("tbl_name") = ml.X
dr("tbl_Id") = ml.Y
dt.Rows.Add(dr)
Next

End Sub
Public Class ModelList
Public Property X() As String
End Property
Public Property Y() As String
End Property
End Class

 

 

posted on 2012-06-15 09:14  疯狂的石头陈  阅读(893)  评论(0编辑  收藏  举报

导航