如何将具有复杂对象的列表转换为数据表 [英] How Can I Convert List With Complex Object To Datatable

查看:61
本文介绍了如何将具有复杂对象的列表转换为数据表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述





我处于将具有复杂对象的列表转换为数据表的情况。

这是我的模型

Hi,

I am in a situation to convert a list with complex object to datatable.
This is my model

public class StudentDetails
{
    public ContactDetails Contact_details { get; set; }
    public Address Address { get; set; }

    public StudentDetails(ContactDetails contactdetails, Address address)
    {
        Contact_details = contactdetails;
        Address = address;
    }
    public StudentDetails()
    {
        Contact_details = new ContactDetails();
        Address = new Address();
    }

}


public class ContactDetails
{
    public string emailID {get; set;}
    public int Age {get; set; }
}
public class Address
{
    public string Address1 { get; set; }
    public string Address2  { get; set; }
}





这是样本列表:



This is sample list:

List<StudentDetails> studentlist = new List<StudentDetails>();
studentlist.Add(new StudentDetails
{
    Address = new Address
    {
        Address1 = "test address1",
        Address2 = "test address32"
    },
    Contact_details = new ContactDetails
    {
        emailID = "test@gmail.com",
        Age = 24
    }
});





现在我想将我的列表(studentlist)转换为DataTable。请给我一个解决方案来解决这个问题。



很快就会回复...

提前致谢。



Now i want to convert my list (studentlist) to DataTable. Please provide me a solution to solve this problem.

Expecting a reply soon...
Thanks in advance.

推荐答案

看看这个:将列表转换为DataTable [ ^ ]


此示例演示如何使用特定架构定义手动创建DataTable:



创建多个DataTable并定义初始列。

创建表约束。

插入值并显示表。

创建表达式列和显示表格。



代码这里





使用System;

使用System.Data ;



class Program {

static void Main(string [] args){

//创建两个表并将它们添加到DataSet中

DataTable orderTable = CreateOrderTable();

DataTable orderDetailTable = CreateOrderDetailTable();

DataSet salesSet = new DataSet ();

salesSet.Tables.Add(orderTable);

salesSet.Tables.Add(orderDetailTable);



//设置表之间的关系并创建相关约束。

salesSet.Relations.Add(OrderOrderDetail,orderTable.Columns [OrderId],orderDetailTable.Columns [OrderId ],true);



Console.WriteLine(创建外键constriant后,如果使用错误的OrderId插入订单明细,您将看到以下错误: );

尝试{

DataRow errorRow = orderDetailTable.NewRow();

errorRow [0] = 1;

errorRow [1] =O0007;

orderDetailTable.Rows.Add(errorRow);

} catch(例外e){

控制台.WriteLine(e.Message);

}

Console.WriteLine();



//插入进入表格的行

InsertOrders(orderTable);

InsertOrderDetails(orderDetailTable);



Console.WriteLine (初始订单表。);

ShowTable(orderTable);



Console.WriteLine(OrderDetail表。) ;

ShowTable(orderDetailTable);



//在子表列上使用Aggregate-Sum来获得结果。

DataColumn colSub = new DataColumn(SubTotal,typeof(Decimal),Sum(Child.LineTotal));

orderTable.Columns.Add(colSub);



//通过引用SubTotal表达式列来计算税收。

DataColumn colTax = new DataColumn(Tax,typeof(Decimal),SubTotal * 0.1);

orderTable.Columns.Add(colTax);



//如果OrderId为'Total',则计算所有订单的到期日;或计算此订单的到期日。

DataColumn colTotal = new DataColumn(TotalDue,typeof(十进制),IIF(OrderId ='Total',Sum(SubTotal)+ Sum(Tax), SubTotal + Tax));

orderTable.Columns.Add(colTotal);



DataRow row = orderTable.NewRow();

row [OrderId] =总计;

orderTable.Rows.Add(row);



Console.WriteLine(具有表达式列的Order表。);

ShowTable(orderTable);



Console.WriteLine( 按任意键退出.....);

Console.ReadKey();

}



private static DataTable CreateOrderTable(){

DataTable orderTable = new DataTable(Order);



//定义一列。

DataColumn colId = new DataColumn(OrderId,typeof(String));

orderTable.Columns.Add(colId);



DataColu mn colDate = new DataColumn(OrderDate,typeof(DateTime));

orderTable.Columns.Add(colDate);



/ /将OrderId列设置为主键。

orderTable.PrimaryKey = new DataColumn [] {colId};



return orderTable; < br $>
}



私有静态DataTable CreateOrderDetailTable(){

DataTable orderDetailTable = new DataTable(OrderDetail);



//一次定义所有列。

DataColumn [] cols = {

new DataColumn( OrderDetailId,typeof(Int32)),

new DataColumn(OrderId,typeof(String)),

new DataColumn(Product,typeof(String)) ,

新DataColumn(UnitPrice,typeof(十进制)),

新DataColumn(OrderQty,ty peof(Int32)),

新DataColumn(LineTotal,typeof(十进制),UnitPrice * OrderQty)

};



orderDetailTable.Columns.AddRange(cols);

orderDetailTable.PrimaryKey = new DataColumn [] {orderDetailTable.Columns [OrderDetailId]};

return orderDetailTable;

}



private static void InsertOrders(DataTable orderTable){

//添加一行一次。

DataRow row1 = orderTable.NewRow();

row1 [OrderId] =O0001;

row1 [ OrderDate] = new DateTime(2013,3,1);

orderTable.Rows.Add(row1);



DataRow row2 = orderTable.NewRow();

row2 [OrderId] =O0002;

row2 [OrderDate] = new DateTime(2013,3,12) ;

orderTable.Rows.Add(row2);



DataRow row3 = orderTab le.NewRow();

row3 [OrderId] =O0003;

row3 [OrderDate] = new DateTime(2013,3,20);

orderTable.Rows.Add(row3);

}



private static void InsertOrderDetails(DataTable orderDetailTable) {

//使用Object数组插入所有行。

//数组中的值按列在表中的显示顺序依次匹配。

Object [] rows = {

new Object [] {1,O0001,Mountain Bike,1419.5,36},

new Object [] {2,O0001,Road Bike, 1233.6,16},

new Object [] {3,O0001,Touring Bike,1653.3,32},

new Object [] {4, O0002,Mountain Bike,1419.5,24},

new Object [] {5,O0002,Road Bike,1233.6,12},

new Object [] {6,O0003,Mountain Bike,1419.5,48},

new Object [] {7,O0003,Touring Bike,1653.3,8},

};



foreach(对象[]行中的行){

orderDetailTable.Rows.Add(行);

}

}



private static void ShowTable(DataTable table){

foreach(Table.Columns中的DataColumn col) ){

Console.Write({0,-14},col.ColumnName);

}

Console.WriteLine() ;



foreach(table.Rows中的DataRow行){

foreach(table.Columns中的DataColumn col){

if(col.DataType.Equals(typeof(DateTime)))

Console.Write({0,-14:d},row [col]);

else if(col.DataType.Equals(typeof(Decimal)))

Console.Write({0,-14:C},row [col]);

else

Console.Write({0,-14},row [col]);

}

Console.WriteLine();

}

Console.WriteLine();

}

}
This sample demonstrates how to create a DataTable manually with specific schema definitions:

Create multiple DataTables and define the initial columns.
Create the table constraints.
Insert the values and display the tables.
Create the expression columns and display the tables.

Code here.


using System;
using System.Data;

class Program {
static void Main(string[] args) {
// Create two tables and add them into the DataSet
DataTable orderTable = CreateOrderTable();
DataTable orderDetailTable = CreateOrderDetailTable();
DataSet salesSet = new DataSet();
salesSet.Tables.Add(orderTable);
salesSet.Tables.Add(orderDetailTable);

// Set the relations between the tables and create the related constraint.
salesSet.Relations.Add("OrderOrderDetail", orderTable.Columns["OrderId"], orderDetailTable.Columns["OrderId"], true);

Console.WriteLine("After creating the foreign key constriant, you will see the following error if inserting order detail with the wrong OrderId: ");
try {
DataRow errorRow = orderDetailTable.NewRow();
errorRow[0] = 1;
errorRow[1] = "O0007";
orderDetailTable.Rows.Add(errorRow);
} catch (Exception e) {
Console.WriteLine(e.Message);
}
Console.WriteLine();

// Insert the rows into the table
InsertOrders(orderTable);
InsertOrderDetails(orderDetailTable);

Console.WriteLine("The initial Order table.");
ShowTable(orderTable);

Console.WriteLine("The OrderDetail table.");
ShowTable(orderDetailTable);

// Use the Aggregate-Sum on the child table column to get the result.
DataColumn colSub = new DataColumn("SubTotal", typeof(Decimal), "Sum(Child.LineTotal)");
orderTable.Columns.Add(colSub);

// Compute the tax by referencing the SubTotal expression column.
DataColumn colTax = new DataColumn("Tax", typeof(Decimal), "SubTotal*0.1");
orderTable.Columns.Add(colTax);

// If the OrderId is 'Total', compute the due on all orders; or compute the due on this order.
DataColumn colTotal = new DataColumn("TotalDue", typeof(Decimal), "IIF(OrderId='Total',Sum(SubTotal)+Sum(Tax),SubTotal+Tax)");
orderTable.Columns.Add(colTotal);

DataRow row = orderTable.NewRow();
row["OrderId"] = "Total";
orderTable.Rows.Add(row);

Console.WriteLine("The Order table with the expression columns.");
ShowTable(orderTable);

Console.WriteLine("Press any key to exit.....");
Console.ReadKey();
}

private static DataTable CreateOrderTable() {
DataTable orderTable = new DataTable("Order");

// Define one column.
DataColumn colId = new DataColumn("OrderId", typeof(String));
orderTable.Columns.Add(colId);

DataColumn colDate = new DataColumn("OrderDate", typeof(DateTime));
orderTable.Columns.Add(colDate);

// Set the OrderId column as the primary key.
orderTable.PrimaryKey = new DataColumn[] { colId };

return orderTable;
}

private static DataTable CreateOrderDetailTable() {
DataTable orderDetailTable = new DataTable("OrderDetail");

// Define all the columns once.
DataColumn[] cols ={
new DataColumn("OrderDetailId",typeof(Int32)),
new DataColumn("OrderId",typeof(String)),
new DataColumn("Product",typeof(String)),
new DataColumn("UnitPrice",typeof(Decimal)),
new DataColumn("OrderQty",typeof(Int32)),
new DataColumn("LineTotal",typeof(Decimal),"UnitPrice*OrderQty")
};

orderDetailTable.Columns.AddRange(cols);
orderDetailTable.PrimaryKey = new DataColumn[] { orderDetailTable.Columns["OrderDetailId"] };
return orderDetailTable;
}

private static void InsertOrders(DataTable orderTable) {
// Add one row once.
DataRow row1 = orderTable.NewRow();
row1["OrderId"] = "O0001";
row1["OrderDate"] = new DateTime(2013, 3, 1);
orderTable.Rows.Add(row1);

DataRow row2 = orderTable.NewRow();
row2["OrderId"] = "O0002";
row2["OrderDate"] = new DateTime(2013, 3, 12);
orderTable.Rows.Add(row2);

DataRow row3 = orderTable.NewRow();
row3["OrderId"] = "O0003";
row3["OrderDate"] = new DateTime(2013, 3, 20);
orderTable.Rows.Add(row3);
}

private static void InsertOrderDetails(DataTable orderDetailTable) {
// Use an Object array to insert all the rows .
// Values in the array are matched sequentially to the columns, based on the order in which they appear in the table.
Object[] rows = {
new Object[]{1,"O0001","Mountain Bike",1419.5,36},
new Object[]{2,"O0001","Road Bike",1233.6,16},
new Object[]{3,"O0001","Touring Bike",1653.3,32},
new Object[]{4,"O0002","Mountain Bike",1419.5,24},
new Object[]{5,"O0002","Road Bike",1233.6,12},
new Object[]{6,"O0003","Mountain Bike",1419.5,48},
new Object[]{7,"O0003","Touring Bike",1653.3,8},
};

foreach (Object[] row in rows) {
orderDetailTable.Rows.Add(row);
}
}

private static void ShowTable(DataTable table) {
foreach (DataColumn col in table.Columns) {
Console.Write("{0,-14}", col.ColumnName);
}
Console.WriteLine();

foreach (DataRow row in table.Rows) {
foreach (DataColumn col in table.Columns) {
if (col.DataType.Equals(typeof(DateTime)))
Console.Write("{0,-14:d}", row[col]);
else if (col.DataType.Equals(typeof(Decimal)))
Console.Write("{0,-14:C}", row[col]);
else
Console.Write("{0,-14}", row[col]);
}
Console.WriteLine();
}
Console.WriteLine();
}
}


这篇关于如何将具有复杂对象的列表转换为数据表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆