如何有效地创建对象列表的一般方法的内? [英] How to efficiently create a list of objects inside of a generic method?
问题描述
所以,我有位于数据库的应用程序。到目前为止,我的查询结果都走进了这样一个DataTable对象:
数据表数据=新的DataTable();
data.Load(someQuery.ExecuteReader());
现在,我想我的加载数据到一个强类型对象的列表。事情是这样的:
名单,其中,MyClass的>数据= someQuery.Load< MyClass的>();
不过,我首先就写一个方法结束了运行速度比DataTable.Load(IDataReader的)的方法要慢近三倍。基本上,我有用户GetConstructor(空).Invoke(空)来创建和对象,我已经使用PropertyInfo.SetValue(reader.GetValue())来填充数据。
有没有更好的方式来做到这一点?
使用的方法:
公开名单< T> LoadData< T>(的DbCommand查询)
{
类型t = typeof运算(T);
名单< T>名单=新的名单,其中,T>();
使用(IDataReader的读卡器= query.ExecuteReader())
{
而(reader.Read())
{
牛逼NEWOBJECT =(T)t.GetConstructor(空).Invoke(空);
对于(INT克拉= 0; CT< reader.FieldCount; CT ++)
{
的PropertyInfo道具= t.GetProperty(reader.GetName(CT));
如果(道具!= NULL)
prop.SetValue(NEWOBJECT,reader.GetValue(CT),NULL);
}
list.Add(NEWOBJECT);
}
}
返回列表;
}
要有效地做到这一点,需要元编程。您可以使用库来帮助。例如,FastMember包括TypeAccessor提供按名称快速访问实例的创建和成员访问。然而,这个例子也基本上究竟是如何短小精悍的作品,所以你可以只的使用短小精悍的:
内部ID = ...
VAR数据= connection.Query<排序>(
选择订单*,其中客户ID = @id
新{ID})了ToList();
您也可以打开短小精悍code,看看它做什么。
So, I have an application which lies on a database. So far, the results of my queries all went into a DataTable object like this:
DataTable data = new DataTable();
data.Load(someQuery.ExecuteReader());
Now, I want to load my data into a list of a strongly typed objects. Something like this:
List<MyClass> data = someQuery.Load<MyClass>();
However, my first take on writing that method ended up running almost three times slower than DataTable.Load(IDataReader) method. Basically, I have user GetConstructor(null).Invoke(null) to create and object and I have used PropertyInfo.SetValue(reader.GetValue()) to fill it with data.
Is there a better way to do this?
The method used:
public List<T> LoadData<T>(DbCommand query)
{
Type t = typeof(T);
List<T> list = new List<T>();
using (IDataReader reader = query.ExecuteReader())
{
while (reader.Read())
{
T newObject = (T)t.GetConstructor(null).Invoke(null);
for (int ct = 0; ct < reader.FieldCount; ct++)
{
PropertyInfo prop = t.GetProperty(reader.GetName(ct));
if (prop != null)
prop.SetValue(newObject, reader.GetValue(ct), null);
}
list.Add(newObject);
}
}
return list;
}
To do this efficiently requires metaprogramming. You can use libraries to help. For example, "FastMember" includes a TypeAccessor which provides fast access to instance creation and member-access by name. However, this example is also basically exactly how "dapper" works, so you could just use dapper:
int id = ...
var data = connection.Query<Order>(
"select * from Orders where CustomerId = @id",
new { id }).ToList();
You can also open up the "dapper" code to see what it does.
这篇关于如何有效地创建对象列表的一般方法的内?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!