我有一个实体列表,其中包含一些与其他实体一样的字段。
例如。
MyEntity
Int id
ContactEntity Contact -> contactId, Name etc…
AddressEntity Address
所以我有 List< MyEntity>
需要转换成数据表。但是我只想从子实体中选择一个字段。
是否可能,或者我是否有任何其他选择。
更新
当我按照 ivowiblo 的描述尝试 CopyToDataTable() 时,出现以下错误
The type 'AnonymousType#1' cannot be used as type parameter 'T' in the generic type or
method 'System.Data.DataTableExtensions.CopyToDataTable<T>(System.Collections.Generic.IEnumerable<T>)'.
There is no implicit reference conversion from 'AnonymousType#1' to 'System.Data.DataRow'.
最佳答案
在http://msdn.microsoft.com/en-us/library/bb669096.aspx他们解释了如何实现一个不需要类型为 DataRow 的 CopyToDataTable()
方法来处理实体等。
只需创建一个返回所需模式的查询并使用 CopyToDataTable()
方法:
var table = entities.Select(x => new {
x.Id,
Contact = x.Contact.Name,
Address = x.Address.Address
}).CopyToDataTable();
此解决方案的唯一问题是它使用反射,它可能会影响性能,具体取决于应用程序的负载。如果您需要避免反射,您将需要创建一个从您的实体显式创建 DataTable 的方法:
var table = new DataTable();
table.Columns.Add("Id", typeof(int))
table.Columns.Add("Contact", typeof(string))
table.Columns.Add("Address", typeof(string))
foreach(var entity in entities) {
var row = table.NewRow();
row["Id"] = entity.Id;
row["Contact"] = entity.Contact.Name;
row["Address"] = entity.Address.Address;
table.Rows.Add(row);
}
关于c# - 数据表的实体列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11156226/