c# - Write similar logic using generics -
i have following method determines cars need delete db.
private list<cardto> buildcarstodelete(ilist<cardto> newcars, ilist<cardto> existingcars) { var missingcars = new list<cardto>(); var cars = newcars.select(c => c.carid); var newcarids = new hashset<int>(cars); foreach (var car in existingcars) { //if there no new cars had , have been removed if (newcars.count() == 0) { missingcars.add(car); } else { if (!newcarids.contains(car.carid)) { missingcars.add(car); } } } return missingcars; }
this works want - if want achieve same functionality customers or apartments of other dtos copying pasting code changing variable names , type of dto around - there nicer way possible using generics keep algorithm , logic allow me use on dto?
if ids of type int
can passing in func
determine id.
private list<t> buildtodelete<t>( ilist<t> newitems, ilist<t> existingitems, func<t, int> getid) { var missingitems = new list<t>(); var items = newitems.select(getid); var newitemids = new hashset<int>(items); foreach (var item in existingitems) { if (newitems.count() == 0) { missingitems.add(item); } else { if (!newitemids.contains(getid(item))) { missingitems.add(item); } } } return missingitems; }
then call shown below:
var results = buildtodelete(newcars, existingcars, c => c.carid);
Comments
Post a Comment