Click here to Skip to main content
15,867,785 members
Articles / Programming Languages / C#

Convert a Collection to a Table

Rate me:
Please Sign up or sign in to vote.
1.89/5 (19 votes)
17 May 2007CPOL1 min read 57.8K   15   7
A collection to table in one function.

Introduction

You could use this code to transfer business objects back to tables and to do XML joins or select statements and filters on them. You could also use an XML serializer to do the same thing. Which is better, that depends. I would say this way, because you have the source, and it's really super simple, and quite fast for small tables. The XML serializer can give you some huge headaches if you have written your own collection class that supports IBindingList. (Actually, there are known bugs in it.) If you have a very large table, you would want to use the XML serializer. (At least, I would hope that it would be more optimized than this way.)

That said, you probably should never be in a situation where you need this, but that is a whole other topic.

Let's get to it.

  1. Use Reflection to resolve the properties of an item in a collection.
  2. C#
    System.Reflection.PropertyInfo [] propInfo = alist[0].GetType().GetProperties();

    Now you have an array of property names (propInfo).

  3. Add those properties as columns to a table:
  4. C#
    dt.Columns.Add(propInfo[i].Name);

What we do now is get the value of the collection item property and set that into the correct row. To do that, invoke the property of the collection's item with InvokeMember.

You will receive an object (object t), and all you have to do is cast that to the correct type and store it in the corresponding row.

Note: This sample just uses ToString, which may not be what you want to do because you have a string as the data type for every column. However, I just use this for creating some reports from business objects, so for that, it works perfectly.

C#
for(int row =0;row < alist.Count ; row++)
{
    dr = dt.NewRow();
    for (int i=0;i< propInfo.Length;i++)
    {
        object tempObject =alist[row];
        object t =tempObject.GetType().InvokeMember(propInfo[i].Name,
                     R.BindingFlags.GetProperty , null,tempObject , new object [] {});

        if (t!=null)
          dr[i] = t.ToString(); 
    }
    dt.Rows.Add(dr);

Complete function

Here is the complete code:

C#
private DataTable CreateDataSource(ArrayList alist) 
{
    DataTable dt = new DataTable();

    if (!alist[0])
        throw new FormatException("Parameter ArrayList empty");

    dt.TableName = alist[0].GetType().Name;
    DataRow dr;
    System.Reflection.PropertyInfo [] propInfo = 
                      alist[0].GetType().GetProperties();

    for(int i=0; i< propInfo.Length;i++)
    {
        dt.Columns.Add(propInfo[i].Name);
    }

    for(int row =0;row < alist.Count ; row++)
    {
        dr = dt.NewRow();

        for (int i=0;i< propInfo.Length;i++)
        {
            object tempObject =alist[row];

            object t =tempObject.GetType().InvokeMember(propInfo[i].Name,
                     R.BindingFlags.GetProperty , null,tempObject , new object [] {});

            if (t!=null)
                dr[i] = t.ToString(); 
        }
        dt.Rows.Add(dr);
    } 
    return dt;
}

License

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


Written By
Software Developer (Senior)
Canada Canada
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
GeneralWorks Grand - once all suggestions are incorporated Pin
pippyn4-Feb-09 4:20
pippyn4-Feb-09 4:20 
GeneralUse IList as parameter type Pin
Dan Herbert31-May-08 4:26
Dan Herbert31-May-08 4:26 
GeneralRe: Use IList as parameter type Pin
rj4531-May-08 8:54
rj4531-May-08 8:54 
GeneralLittle improvement Pin
Anonymous8-Jun-05 0:44
Anonymous8-Jun-05 0:44 
GeneralGetValue Pin
Corneliu Tusnea28-Apr-04 15:54
Corneliu Tusnea28-Apr-04 15:54 
GeneralRe: GetValue Pin
rj4528-Apr-04 18:27
rj4528-Apr-04 18:27 
GeneralRe: GetValue Pin
leeym200428-Sep-05 22:35
leeym200428-Sep-05 22:35 

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.