Fastest way to convert datatable to generic list

后端 未结 6 730
逝去的感伤
逝去的感伤 2020-12-01 15:30

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 wa

6条回答
  •  一个人的身影
    2020-12-01 15:55

    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 data = new List(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...)

提交回复
热议问题