Tôi có danh sách lồng nhau và tôi cần chuyển đổi nó thành Số liệu trong C#. Tôi tìm thấy nhiều ví dụ về điều này nhưng họ không làm những gì tôi cần. Tôi có một danh sách trong một danh sách, tôi cần danh sách lồng nhau trong một DataTable khác trong DataSet.Cách chuyển Danh sách lồng nhau thành Tập dữ liệu trong C#
Dưới đây là một ví dụ về danh sách
public class InvoiceResponse(){
public string BillToName { get; set; }
public string BillToAddr1 { get; set; }
...
...
public List<InvoiceItemResponse> Items { get; set; }
}
Tôi đã sử dụng mã dưới đây để chuyển đổi danh sách to DataSet nhưng Nó didnt chuyển đổi mục để DataTable trong DataSet
public DataSet CreateDataSet<T>(List<T> list)
{
//list is nothing or has nothing, return nothing (or add exception handling)
if (list == null || list.Count == 0) { return null; }
//get the type of the first obj in the list
var obj = list[0].GetType();
//now grab all properties
var properties = obj.GetProperties();
//make sure the obj has properties, return nothing (or add exception handling)
if (properties.Length == 0) { return null; }
//it does so create the dataset and table
var dataSet = new DataSet();
var dataTable = new DataTable();
//now build the columns from the properties
var columns = new DataColumn[properties.Length];
for (int i = 0; i < properties.Length; i++)
{
columns[i] = new DataColumn(properties[i].Name, properties[i].PropertyType);
}
//add columns to table
dataTable.Columns.AddRange(columns);
//now add the list values to the table
foreach (var item in list)
{
//create a new row from table
var dataRow = dataTable.NewRow();
//now we have to iterate thru each property of the item and retrieve it's value for the corresponding row's cell
var itemProperties = item.GetType().GetProperties();
for (int i = 0; i < itemProperties.Length; i++)
{
dataRow[i] = itemProperties[i].GetValue(item, null);
}
//now add the populated row to the table
dataTable.Rows.Add(dataRow);
}
//add table to dataset
dataSet.Tables.Add(dataTable);
//return dataset
return dataSet;
}
Làm thế nào tôi có thể chuyển đổi Danh sách các mục vào một DataTable khác vào DataSet?
thử trong khi điều này trở về dữ liệu 'trở dataset.GetXml(); ' –