我有一个包含任务的课程:
class Task{
public string Description;
public DateTime StartDate;
public DateTime EndDate;
}
我有一个SQLite数据库,其DataTable
名为“任务”:
DataTable.Rows[0]["Description"].ToString() // "Draw a cat"
DataTable.Rows[0]["BeginDate"].ToString() // "2016-08-17 9:47:22 AM"
DataTable.Rows[0]["EndDate"].ToString() // "2016-08-17 11:22:37 AM"
我可以创建从DataTable中填充的List<Task>
吗?
我可以向Task
添加新的List<Task>
并让它更新DataTable吗?
答案 0 :(得分:1)
我可以创建从DataTable填充的List吗?
你需要这样的代码才能做到这一点:
// Creates IEnumerable<DataRow>
var taskDataTableEnumerable = taskDataTable.AsEnumerable();
List<Task> myTaskList =
(from item in taskDataTableEnumerable
select new Task{
Description = item.Field<string>("DescriptionColumnName"),
StartDate = item.Field<DateTime>("StartDateColumnName"),
EndDate = item.Field<DateTime>("EndDateColumnName")
}).ToList();
我可以向List添加一个新任务并让它更新DataTable吗?
是的,您可以,并且您有以下选择:
FastMember
来实现相同的目标或者
您只需在现有表格中创建一个新的DataRow
,如下所示:
DataRow taskDataRow = taskDataTable.NewRow();
使用如下代码从新添加的任务对象向taskDataRow添加数据:
taskDataRow["DescriptionColumnName"] = taskObject.Description
taskDataRow["StartDateColumnName"] = taskObject.StartDate
taskDataRow["EndDateColumnName"] = taskObject.EndDate
这种方式新添加的Task
对象也会DataRow
添加到DataTable
FastMember
,以防type T
对您的用例不起作用您需要一个不同的选项,然后可能计划使用下面的自定义代码,其中所有DataTable
属性将转换为具有适当列名的 public static DataTable CreateTable<TDataTable>(this IEnumerable<TDataTable> collection)
{
// Fetch the type of List contained in the ParamValue
var tableType = typeof(TDataTable);
// Create DataTable which will contain data from List<T>
var dataTable = new DataTable();
// Fetch the Type fields count
var columnCount = tableType.GetProperties().Count();
var columnNameMappingDictionary = new Dictionary<string, string>();
// Create DataTable Columns using table type field name and their types
// Traversing through Column Collection
for (var counter = 0; counter < columnCount; counter++)
{
var propertyInfo = tableType.GetProperties()[counter];
// Fetch DataParam attribute
var dataParameterAttribute = propertyInfo.GetDataParameterAttribute();
// Datatable column name based on DataParam attribute
var columnName = (dataParameterAttribute != null) ? dataParameterAttribute.Name : propertyInfo.Name;
columnNameMappingDictionary.Add(propertyInfo.Name,
(dataParameterAttribute != null) ? dataParameterAttribute.Name : propertyInfo.Name);
// Fetch the current type of a property and check whether its nullable type before adding a column
var currentType = tableType.GetProperties()[counter].PropertyType;
dataTable.Columns.Add(columnName, Nullable.GetUnderlyingType(currentType) ?? currentType);
}
// Return parameter with null value
if (collection == null)
return dataTable;
// Traverse through number of entries / rows in the List
foreach (var item in collection)
{
// Create a new DataRow
var dataRow = dataTable.NewRow();
foreach (var columnName in columnNameMappingDictionary.Select(propertyinfo => propertyinfo.Value))
{
dataRow[columnName] = item.GetType().GetProperty(columnName).GetValue(item) ?? DBNull.Value;
}
// Add Row to Table
dataTable.Rows.Add(dataRow);
}
return (dataTable);
}
,您可以根据需要添加字段选项,目前它是属性:
[AttributeUsage(AttributeTargets.Property, AllowMultiple = true)]
public class DataParamAttribute : Attribute
{
/// <summary>
/// Gets or sets the name.
/// </summary>
public string Name { get; set; }
/// <summary>
/// Initializes a new instance of the <see cref="DataParamAttribute"/> class.
/// </summary>
/// <param name="name">
/// The name.
/// </param>
public DataParamAttribute(string name)
{
this.Name = name;
}
}
//数据参数属性
public static DataParamAttribute GetDataParameterAttribute(this PropertyInfo propertyInfo)
{
DataParamAttribute mappedAttribute = null;
// Get list of Custom Attributes on a property
var attributeArray = propertyInfo.GetCustomAttributes(false);
// Column mapping of the ParameterAttribute
var columnMapping =
attributeArray.FirstOrDefault(attribute => attribute.GetType() == typeof(DataParamAttribute));
if (columnMapping != null)
{
// Typecast to get the mapped attribute
mappedAttribute = columnMapping as DataParamAttribute;
}
return mappedAttribute;
}
//获取DataParameter属性
picker.delegate = self;