c# - LINQ to map a datatable into a list<MyObject> -
i discover linq comprehensive me please! :-)
so! have data-tier provide me datatables , want convert them lists of objects. these objects defined in spécific layer dto (data transfer objects).
how can map every rows of datatable objects , put objects list? (today make "manually" field after field) possible linq? i've heard linq2entities? right?
thanks beginner understand...
if objects not complex can use this:
public static class datatableextensions { public static ilist<t> tolist<t>(this datatable table) 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) t : new() { t item = new t(); foreach (var property in properties) { property.setvalue(item, row[property.name], null); } return item; } }
with in place can write: var list = yourdatatable.tolist<yourentitytype>()
.
you can read here: http://blog.tomasjansson.com/convert-datatable-to-generic-list-extension/
and answer previous question: convert datatable generic list in c#
edit: should add not linq, extension methods datatable
wrote. also, working convention properties in object you're mapping has same name in datatable. of course extended read attributes on properties or method take simple dictionary<string,string>
used mapping. extend functionality take params string[] excludeproperties
used exclude of properties.
Comments
Post a Comment