asp.net - Any way I can make this code cleaner/more efficient? (C#/LINQ-to-SQL) -
i've been putting auditing solution program developing, using linq update/insert operations. have come following solution (this snippet inserting) (note tables variable contains list of tables have been modified - add these list manually , call method):
bindingflags b = bindingflags.instance | bindingflags.public; linqdatacontext dc = new linqdatacontext(); foreach (object table in tables) { string tablename = table.tostring().replace("project.", ""); switch (tablename) { case "job": string newjobstring = null; job jobdetails = (job)table; var prpsjob = typeof(job).getproperties(b); foreach (var p in prpsjob) { object x = p.getgetmethod().invoke(jobdetails, null); x = stripdate(x); newjobstring += p.name + ": " + x + environment.newline; } audit(jobid, newjobstring, "new job created", sourceid, "", jobdetails.jobid); break; case "estimation": string newestimationsstring = null; estimation estimationdetails = (estimation)table; var prpsestimations = typeof(estimation).getproperties(b); foreach (var p in prpsestimations) { object x = p.getgetmethod().invoke(estimationdetails, null); x = stripdate(x); newestimationsstring += p.name + ": " + x + environment.newline; } audit(jobid, newestimationsstring, "new estimation created", sourceid, "", estimationdetails.estimationid); break;
and code goes on each possible tablename. code works fine, seems inefficient - having identical block each case. there more efficient way?
you should able use lambdas cover type-specific parts of repeated code. pseudo-code hacked together....
void tableisjob(job j, bindingflags b) { handletable("job", j.jobid, typeof(job).getproperties(b), p=>p.getgetmethod().invoke(j, null)); } void tableisestimation(estimation e, bindingflags b) { handletable("estimation", e.estimationid, typeof(estimation).getproperties(b), p => p.getgetmethod().invoke(e, null)); } void handletable(string nm, int id, propertyinfo [] props, func<propertyinf, object> i) { string desc = string.join(environment.newline, props.select(p=>{ return string.format("{0}: {1}", p.name, stripdate(i(p))); }).toarray()); audit(jobid, desc, string.format("new {0} created", nm), sourceid, "", id); }
and can replace huge loop , switch case with...
tables.select(t => { switch (t.tostring().replace("project.", "")) { case "job": tableisjob((job)t, b); break; case "estimation": tableisestimation((estimation)t, b); break; } });
this assuming "efficient" means in terms of code volume, not in execution time.
Comments
Post a Comment