尝试使用这样的扩展:
public static class Extesions
{
public static DataSet ToDataSet<T>(this IList<T> list)
{
Type elementType = typeof(T);
DataSet ds = new DataSet();
DataTable t = new DataTable();
ds.Tables.Add(t);
//add a column to table for each public property on T
foreach (var propInfo in elementType.GetProperties())
{
Type ColType = Nullable.GetUnderlyingType(propInfo.PropertyType) ?? propInfo.PropertyType;
t.Columns.Add(propInfo.Name, ColType);
}
//go through each property on T and add each value to the table
foreach (T item in list)
{
DataRow row = t.NewRow();
foreach (var propInfo in elementType.GetProperties())
{
row[propInfo.Name] = propInfo.GetValue(item, null) ?? DBNull.Value;
}
t.Rows.Add(row);
}
return ds;
}
}
用法:
public class Entity
{
public int CompanyId { get; set; }
public DateTime EndDate { get; set; }
public DateTime StartDate { get; set; }
public int DateId { get; set; }
}
// ...
List<Entity> res = dbconnect.tblManageDates.Where(i => i.internationalCode == _international).Select(i => new Entity
{
CompanyId = i.companyId,
EndDate = i.endDate,
StartDate = i.startDate,
DateId = i.dateId
}).ToList();
DataSet dataSet = res.ToDataSet();