linq - c# How can I create a collection of custom objects without going through each field -


i have created class called dataresponse has more 40 public fields. class dataresponse has same number of fields , type what's in database datarepoes (let's assume that).

is there way @ linq below create list of objects , automatically fields assigned dataresponse what's in db? otherwise have spell out each , every 40 fields , assign them manually when new dataresponse class. thanks

list<classes.dataresponse> res = (from rx in con.datarepoes   iaccess.contains(rx.storeid)   select new classes.dataresponse).tolist<classes.dataresponse>(); 

if don't need flexibility provided automapper or don't want using third party library, can use following simplified custom extension method:

public static class queryableextensions {     public static iqueryable<tresult> selectto<tresult>(this iqueryable source)     {         var sourcetype = source.elementtype;         var resulttype = typeof(tresult);         var parameter = expression.parameter(sourcetype, "x");         var bindings =             rm in resulttype.getproperties().concat<memberinfo>(resulttype.getfields())             join sm in sourcetype.getproperties().concat<memberinfo>(sourcetype.getfields())                 on rm.name equals sm.name             select expression.bind(rm, expression.makememberaccess(parameter, sm));         var body = expression.memberinit(expression.new(resulttype), bindings);         return source.provider.createquery<tresult>(expression.call(             typeof(queryable), "select", new[] { sourcetype, resulttype },             source.expression, expression.quote(expression.lambda(body, parameter))));     } } 

it try select properties/fields match name. fail if matched property/field types differ.

sample usage:

method syntax

var res = con.datarepoes     .where(rx => iaccess.contains(rx.storeid))     .selectto<classes.dataresponse>()     .tolist(); 

query syntax

var res =     (from rx in con.datarepoes      iaccess.contains(rx.storeid)      select rx)     .selectto<classes.dataresponse>()     .tolist(); 

Comments