views:

4806

answers:

4

I have a data tier select method that returns a datatable. It's called from a business tier method that should then return a strongly typed generic List.

What I want to do is very similar (but not the same as) this question:
http://stackoverflow.com/questions/208532/how-do-you-convert-a-datatable-into-a-generic-list

What's different is that I want the list to contain strongly-typed objects rather than datarows (also, I don't have linq avaiable here yet).

I'm concerned about performance. The business tier method will in turn be called from the presentation tier, and the results will be iterated for display to the user. It seems very wasteful to add an extra iteration at the business tier, only do it again right away for the presentation, so I want this to be as quick as possible.

This is a common task, so I'm really looking for a good pattern that can be repeated over and over.

+2  A: 

Do you know the structure of the DataTable and the typed object ahead of time? You could use a delegate to do the mapping. If you don't (i.e. all you know is a Type and properties) there are ways of accelerating dynamic member access (such as HyperDescriptor).

Either way, consider an iterator block; that way you don't have to buffer the objects an entire second time; of course, if you are only dealing with smallish rowcounts this isn't an issue.

Can you clarify any of those points? I can add a lot more detail...

At the simplest, what is wrong with:

        DataTable table = new DataTable {
            Columns = {
                {"Foo", typeof(int)},
                {"Bar", typeof(string)}
             }
        };
        for (int i = 0; i < 5000; i++) {
            table.Rows.Add(i, "Row " + i);
        }

        List<MyType> data = new List<MyType>(table.Rows.Count);
        foreach (DataRow row in table.Rows) {
            data.Add(new MyType((int)row[0], (string)row[1]));
        }

(the problems in the above might steer the right approach...)

Marc Gravell
Nothing wrong with it: it just seems very klunky, like there ought to be a better way.
Joel Coehoorn
@Joel - well, you could use a `Converter<DataRow,MyType>`, but without knowing what problem we're trying to solve...
Marc Gravell
A: 

You will need to iterate through the datarows and convert them into your objects at some time anyway, but you could write a custom collection with a constructor that takes a collection of datarows and that converts each item into your object type when requested instead of all at once.

Say you define your custom collection that implements IList<T>. It could then have two internal fields - a reference to the collection of datarows and a List<T>. The List<T> would be initialized to the length of the collection of datarows but with null values.

Now in the indexer you could check if the List<T> contains a value at that index and if not you could create the object using whatever means would be useful and store it there before returning it.

This would postpone the creation of your objects until they were requested and you would only create the objects that were requested.

Your objects would probably need a constructor taking a DataRow or you would need some sort of factory to create them, but that is another topic.

Rune Grimstad
A: 

Just to provide some more user - friendliness to Mark's answer in a simple console app :

  using System;
using System.Collections.Generic;
using System.Text;
using System.Data;

namespace ConvertDataTableIntoListOfObjects
{
class Program
{
    static void Main(string[] args)
    {

        //define a DataTable obj
        DataTable table = new DataTable
        {
            Columns = {
            {"Foo", typeof(int)},
            {"Bar", typeof(string)}
         }
        };
        //populate it the DataTable 
        for (int i = 0; i < 3; i++)
        {
            table.Rows.Add(i, "Row " + i);
        }

        //
        List<MyType> listWithTypedObjects= new List<MyType>(table.Rows.Count);
        foreach (DataRow row in table.Rows)
        {
            listWithTypedObjects.Add(new MyType((int)row[0], (string)row[1]));
        }


        Console.WriteLine(" PRINTING THE POPULATED LIST ");
        foreach (MyType objMyType in listWithTypedObjects)
        {
            Console.Write(" I have object of the type " + objMyType.ToString() + " => " );
            Console.Write(" with Prop1OfTypeInt " + objMyType.Prop1OfTypeInt.ToString() + " , ");
            Console.WriteLine(" with Prop1OfTypeInt " + objMyType.Prop2OfTypeString.ToString() + "  "); 
        }

        Console.WriteLine(" \n \n \n HIT A KEY TO EXIT THE PROGRAM ");
        Console.ReadKey();
    } //eof method 
} //eof class 


class MyType {

    public int Prop1OfTypeInt { get; set; }
    public string Prop2OfTypeString { get; set; } 

    /// <summary>
    /// Note the order of the passed parameters is important !!!
    /// </summary>
    /// <param name="prop1OfTypeInt"></param>
    /// <param name="prop2OfTypeString"></param>
    public MyType( int prop1OfTypeInt , string prop2OfTypeString)
    {
        this.Prop1OfTypeInt = prop1OfTypeInt;
        this.Prop2OfTypeString = prop2OfTypeString; 

    } //eof const

} //eof class 
} //eof namespace 
YordanGeorgiev
A: 

The problem with the sample above is that it is terribly slow. I have a DataTable with about 400 rows and this conversion takes a good 5 or 6 seconds!

It does seem like a pretty common task, so I'm surprised to not see someone here with a more performant solution.

* Update!! * Just for kicks, I thought I would try converting using LINQ instead of iterating through the DataTable and adding to my List. The following is what I did:

   List<MyObject> returnList = new List<MyObject>();

   MyDataTable dtMyData = new MyTableAdapter().GetMyData();

   returnLists = (from l in dtMyData
                 select new MyObject
                 {
                    Active = l.IsActive,
                    Email = l.Email,
                    //...
                    //About 40 more properties
                    //...
                    ZipCode = l.Zipcode
                  }).ToList();

The first method (iterating through each row) took 5.3 seconds and the method using LINQ took 1.8 seconds!

John