c# - Dynamic Remove Function -
i have following code works more reusable or getting same results. rather remove_at_weight
, remove_at_code
function generic remove
function can choose field compare , compare against.
so example might have object called recordo_3
has third field "string description" , want check field out having write new "remove_at_description" function.
i approaching wrong angle , there better way of doing using design patten etc. if please advise. hope makes sense.
class recordo { private string _code; public string code { { return _code; } set { _code = value; } } private int _weight; public int weight { { return _weight; } set { _weight = value; } } } private void form1_load(object sender, eventargs e) { list<recordo> lr = new list<recordo>(); lr.add(new recordo() {code = "qqq", weight = 10}); lr.add(new recordo() { code = "aaa", weight = 20 }); lr.add(new recordo() { code = "aaa", weight = 10 }); lr.add(new recordo() { code = "qqq", weight = 10 }); lr = remove_at_code(lr,"qqq"); lr = remove_at_weight(r, "20"); messagebox.show("done!"); } private static list<recordo> remove_at_weight(list<recordo> lr, int weight) { (int = lr.count-1; > -1; i--) { if (lr[i].weight == weight) { lr.removeat(i); } } return lr; } private static list<recordo> remove_at_code(list<recordo> lr, string code) { (int = lr.count-1; > -1; i--) { if (lr[i].code == code) { lr.removeat(i); } } return lr; }
first let's without generic method have asked (for might consider reflection property name - see below). work can done in simple way using linq
this
lr.removeall(r => r.code.equals("qqq")); lr.removeall(r => r.weight == 20);
now if want generic method, can try this
public static class myextension { public static void removeallwithpropertyvalue<t>(this list<t> list, string propertyname, object value) { var property = typeof(t).getproperty(propertyname); list.removeall(item => property.getvalue(item, null).equals(value)); } }
and use custom extension as
lr.removeallwithpropertyvalue("code", "qqq"); lr.removeallwithpropertyvalue("weight", 20);
note: not type-safe, , didn't validation!
Comments
Post a Comment