最快的转换数据表到泛型列表的方法数据表、最快、方法、列表

2023-09-02 10:26:53 作者:别留我孤身一人

我有一个返回DataTable中的一个数据层选择方法。这就是所谓的从业务层的方法,应该然后返回一个强类型的泛型列表。

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.

我想要做的是非常相似(但不一样)这个问题: http://stackoverflow.com/questions/208532/how-do-you-convert-a-datatable-into-a-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

以往不同的是,我想列表中包含强类型的对象,而不是数据行(也,我没有LINQ缴费到现在还没有)。

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).

我很担心性能。业务层方法,将依次从presentation层调用,将结果迭代显示给用户。它似乎很浪费,在业务层,只能再做一次马上为presentation添加一个额外的迭代,所以我想这是尽可能快。

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.

推荐答案

你知道数据表和提前时间的类型对象的结构?你可以使用一个委托来进行映射。如果不这样做(即所有你知道的是键入和属性)有加速动态成员访问(如 HyperDescriptor )。

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).

无论哪种方式,考虑一个迭代器块;这样你就不必缓冲对象的整个第二时间;当然,如果你只处理短小rowcounts这不是一个问题。

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...)