huM*_*pty 10 c# datatable .net-4.0
我有一个实体列表,其中包含一些字段作为其他实体.
例如.
MyEntity
Int id
ContactEntity Contact -> contactId, Name etc…
AddressEntity Address
Run Code Online (Sandbox Code Playgroud)
所以我List< MyEntity>需要将其转换为数据表.但是从子实体我只想选择一个字段.
是否有可能或者我有其他选择.
UPDATE
当我尝试使用 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'.
Run Code Online (Sandbox Code Playgroud)
Ivo*_*Ivo 16
在http://msdn.microsoft.com/en-us/library/bb669096.aspx中,他们解释了如何实现一种CopyToDataTable()方法,该方法不需要将类型作为DataRow来处理,例如,实体.
只需创建一个返回所需模式和使用CopyToDataTable()方法的查询:
var table = entities.Select(x => new {
x.Id,
Contact = x.Contact.Name,
Address = x.Address.Address
}).CopyToDataTable();
Run Code Online (Sandbox Code Playgroud)
此解决方案的唯一问题是它使用反射,它可能会影响性能,具体取决于您的应用程序的负载.如果需要避免反射,则需要创建一个从您的实体显式创建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);
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
23255 次 |
| 最近记录: |