LINQ映射数据表到一个列表<&MyObject的GT;
我才发现LINQ,所以要综合请与我! : - )
I just discover LINQ so be comprehensive with me please! :-)
所以!我有一个数据层提供谁我数据表,我想将它们转换成对象名单。这些对象在特定层DTO(数据传输对象)中定义的。
So! I have a Data-tier who provide me datatables and i want to convert them into lists of objects. These objects are defined in a spécific layer DTO (Data transfer Objects).
如何将我的DataTable的每一行到对象映射,并把所有的对象到一个列表? (今天我使其手动字段后场)
是否有可能与LINQ?我听说过LINQ2Entities?对吗?
How can I map every rows of my datatable into objects and put the all objects into a list? (today i make it "manually" field after field) Is it possible with LINQ? I've heard about LINQ2Entities? am i right?
感谢帮助初学者了解...
Thanks to help a beginner to understand...
如果对象是不是太复杂,你可以使用这样的:
If the objects is not too complex you can use this:
public static class DataTableExtensions
{
public static IList<T> ToList<T>(this DataTable table) where T : new()
{
IList<PropertyInfo> properties = typeof(T).GetProperties().ToList();
IList<T> result = new List<T>();
foreach (var row in table.Rows)
{
var item = CreateItemFromRow<T>((DataRow)row, properties);
result.Add(item);
}
return result;
}
private static T CreateItemFromRow<T>(DataRow row, IList<PropertyInfo> properties) where T : new()
{
T item = new T();
foreach (var property in properties)
{
property.SetValue(item, row[property.Name], null);
}
return item;
}
}
通过在地方,你可以这样写: VAR列表= YourDataTable.ToList< YourEntityType>()
With that in place you can now write: var list = YourDataTable.ToList<YourEntityType>()
.
您可以在这里读到它:的http://blog.tomasjansson.com/convert-datatable-to-generic-list-extension/
You can read about it here: http://blog.tomasjansson.com/convert-datatable-to-generic-list-extension/
和它是一个回答上一个问题:的转换为数据表泛型列表在C#
And it is an answer to a previous question: Convert DataTable to Generic List in C#
编辑:我要补充一点,这不是LINQ ,但一些扩展方法数据表
我写的。此外,它正在与在你与映射对象的属性具有相同的名称作为DataTable中的约定。当然,这可以被扩展到阅读的属性或方法本身的属性可以采取一个简单的词典<字符串,字符串>
,可以用来做映射。你也可以用一些功能,采取了 PARAMS字符串[] excludeProperties
,可以用来排除某些属性。
I should add that this is not linq, but some extension methods to DataTable
I wrote. Also, it is working with the convention that the properties in the object you're mapping with has the same name as in the DataTable. Of course this could be extended to read attributes on the properties or the method itself could take a simple Dictionary<string,string>
that could be used to do the mapping. You could also extend it with some functionality that take a params string[] excludeProperties
that could be used to exclude some of the properties.