Click here to Skip to main content
15,896,063 members
Articles / DataAdapter
Tip/Trick

Convert EntityCollection to DataTable

Rate me:
Please Sign up or sign in to vote.
0.00/5 (No votes)
26 Feb 2013CPOL 33.4K   2   2
Code for converting the EntityCollection of a DataTable.

Introduction

This tips gives code for converting the EntityCollection of a DataTable.

Using the code

The Dynamics CRM 2011 RetriveMultiple method returns an EntityCollection. The below code is to convert th EntityCollection to a DataTable.

C#
//Get records returns the Entity Collection
public DataTable GetDataTable()
{
    EntityCollection accountRecords = GetAccountRecords();
    DataTable dTable = new DataTable();
    int iElement = 0;

    if (accountRecords.Entities.Count >= 0)
    {
        return;
    }

    //Defining the ColumnName for the datatable
    for (iElement = 0; iElement <= accountRecords.Entities[0].Attributes.Count - 1; iElement++)
    {
        string columnName = accountRecords.Entities[0].Attributes.Keys.ElementAt(iElement);
        dTable.Columns.Add(columnName);
    }

    foreach (Entity entity in accountRecords.Entities)
    {
        DataRow dRow = dTable.NewRow();
        for (int i = 0; i <= entity.Attributes.Count - 1; i++)
        {
            string colName = entity.Attributes.Keys.ElementAt(i);
            dRow[colName] = entity.Attributes.Values.ElementAt(i);
        }
        dTable.Rows.Add(dRow);
    }
    return dTable;
}

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



Comments and Discussions

 
BugLogic and Syntax Error Pin
Ryan Daniels19-Mar-15 7:30
Ryan Daniels19-Mar-15 7:30 
SuggestionSame idea generalised to IEnumerable on MSDN Blog Pin
Jerome Vibert27-Feb-13 20:45
Jerome Vibert27-Feb-13 20:45 
You can have a look at the same idea generalised to IEnumerable at this place : http://blogs.msdn.com/b/aconrad/archive/2007/09/07/science-project.aspx[^]
Entities are IEnumerable, so you can use it in your context.
I've not tested performances.

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.