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

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

问题描述

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



我想做的是非常相似(但不一样)这个问题:

如何转换数据表转换成通用列表?



有什么不同,我希望列表包含强类型的对象而不是数据行(也是,我没有linq avaiable这里)



我关心的是性能。业务层方法又将从表示层调用,结果将被迭代显示给用户。在业务层添加一个额外的迭代似乎是非常浪费的,只是为了演示文稿而立即做到这一点,所以我想要尽可能的快。



这是一个常见的任务,所以我真的在寻找一种可以反复反复的好的模式。

解决方案

您提前知道 DataTable 和类型对象的结构?您可以使用委托来做映射。如果你没有(即所有你知道的是一个类型和属性)有加速动态成员访问(例如 HyperDescriptor )。



无论哪种方式,都要考虑迭代器块;这样你就不必一次缓冲对象了;当然,如果你只是处理小行数,这不是一个问题。



你能澄清这些要点吗?我可以添加更多的细节...



最简单的是,有什么问题:

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

}

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

(上述问题可能会引导正确的方法...) / p>

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

解决方案

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

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

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