List of entities to datatable

28,579

In http://msdn.microsoft.com/en-us/library/bb669096.aspx they explain how to implement a CopyToDataTable() method that doesn't need the type to be a DataRow for working with, for instance, entities.

Just create a query that returns the desired schema and use CopyToDataTable() method:

var table = entities.Select(x => new {
                                       x.Id,
                                       Contact = x.Contact.Name,
                                       Address = x.Address.Address
                                      }).CopyToDataTable();

The only issue with this solution is that it uses reflection and it may hit the performance, depending on the load of you application. If you need to avoid reflection, you will need to create a method that explicitly creates the DataTable from you entities:

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);
}
Share:
28,579
huMpty duMpty
Author by

huMpty duMpty

.NET Developer Web LinkedIn

Updated on December 02, 2020

Comments

  • huMpty duMpty
    huMpty duMpty over 3 years

    I have a list of entities which contain some of it fields as other entities.

    Eg.

    MyEntity
    Int id
    ContactEntity Contact -> contactId, Name etc…
    AddressEntity Address
    

    So I have List< MyEntity> which needs to be converted to a data table. But from the sub entities I want only one field to be selected.

    Is it possible or do I have any other alternative.

    UPDATE

    When I try CopyToDataTable() as ivowiblo describes it gives me following error

     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'.
    
  • huMpty duMpty
    huMpty duMpty about 12 years
    Yes, I have seen the msdn.microsoft.com/en-us/library/bb669096.aspx, problem is I have sub entities within the entity and I only need to extract one filed from those
  • Marc.2377
    Marc.2377 about 5 years
    I find the FastMember library by Marc Gravell very useful for this task. Refer to the related question to see how it can be done.
  • Kiquenet
    Kiquenet over 3 years
    @Marc.2377 full sample using FastMember about it?
  • Marc.2377
    Marc.2377 over 3 years
    @Kiquenet See link in comment under the question.