mez*_*oid 15 c# transformation list dataset
给定一个对象列表,我需要将其转换为数据集,其中列表中的每个项目由一行表示,每个属性都是行中的一列.然后将此DataSet传递给Aspose.Cells函数,以便将Excel文档创建为报表.
说我有以下内容:
public class Record
{
public int ID { get; set; }
public bool Status { get; set; }
public string Message { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
给定List记录,如何将其转换为DataSet,如下所示:
ID Status Message
1 true "message"
2 false "message2"
3 true "message3"
...
Run Code Online (Sandbox Code Playgroud)
目前我能想到的唯一一件事如下:
DataSet ds = new DataSet
ds.Tables.Add();
ds.Tables[0].Add("ID", typeof(int));
ds.Tables[0].Add("Status", typeof(bool));
ds.Tables[0].Add("Message", typeof(string));
foreach(Record record in records)
{
ds.Tables[0].Rows.Add(record.ID, record.Status, record.Message);
}
Run Code Online (Sandbox Code Playgroud)
但这种方式让我觉得必须有一个更好的方法,因为至少如果将新属性添加到Record中,那么它们将不会显示在DataSet中......但同时它允许我控制每个属性被添加到行中.
有谁知道更好的方法吗?
CMS*_*CMS 30
您可以通过反射和泛型来检查基础类型的属性.
考虑我使用的这种扩展方法:
public static DataTable ToDataTable<T>(this IEnumerable<T> collection)
{
DataTable dt = new DataTable("DataTable");
Type t = typeof(T);
PropertyInfo[] pia = t.GetProperties();
//Inspect the properties and create the columns in the DataTable
foreach (PropertyInfo pi in pia)
{
Type ColumnType = pi.PropertyType;
if ((ColumnType.IsGenericType))
{
ColumnType = ColumnType.GetGenericArguments()[0];
}
dt.Columns.Add(pi.Name, ColumnType);
}
//Populate the data table
foreach (T item in collection)
{
DataRow dr = dt.NewRow();
dr.BeginEdit();
foreach (PropertyInfo pi in pia)
{
if (pi.GetValue(item, null) != null)
{
dr[pi.Name] = pi.GetValue(item, null);
}
}
dr.EndEdit();
dt.Rows.Add(dr);
}
return dt;
}
Run Code Online (Sandbox Code Playgroud)