将数据表转换为通用列表的最快方法 [英] Fastest way to convert datatable to generic list

查看:25
本文介绍了将数据表转换为通用列表的最快方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个返回数据表的数据层选择方法.它从业务层方法调用,然后应返回强类型泛型列表.

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.

我想做的与这个问题非常相似(但不一样):
如何将 DataTable 转换为通用列表?

What I want to do is very similar (but not the same as) this question:
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).

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

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.

推荐答案

你是否提前知道DataTable的结构和类型化对象?您可以使用委托来进行映射.如果您不知道(即您只知道 Type 和属性),则有多种方法可以加速动态成员访问(例如 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).

不管怎样,考虑一个迭代器块;这样你就不必第二次缓冲对象;当然,如果您只处理较小的行数,这不是问题.

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

这篇关于将数据表转换为通用列表的最快方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆