c# - Generalize a function -
i trying figure out if there way generalize function takes hashset of 2 unrelated objects similar attributes. have sample code below:
private ilist<idictionary<string, string>> builddictionary(hashset<classa> classa) { ilist<idictionary<string, string>> data = new list<idictionary<string, string>>(); foreach (var in classa) { dictionary<string, string> adictionary = new dictionary<string, string>(); adictionary.add(a.code, a.code + "," + a.name); data.add(adictionary); } return data; } private ilist<idictionary<string, string>> builddictionary(hashset<classb> classb) { ilist<idictionary<string, string>> data = new list<idictionary<string, string>>(); foreach (var b in classb) { dictionary<string, string> bdictionary = new dictionary<string, string>(); bdictionary.add(b.code, b.code + "," + b.name); data.add(bdictionary); } return data; }
thus evident code, 2 classes not related both in hashset , contain similar attributes (code, name). have tried using generic t failed due fact don't have generic class t created. there anyway around issue without creating new class?
if source classes sealed or can't modified common interface, can use accessors parts needed, 1 might in linq queries.
here's example implementation. note tokey()
, tomembervalue()
named more appropriately, enough replicate doing class can specify lambda retrieve relevant property, , isn't dependent upon class having same property names long lambda written accordingly. main()
shows use method both cases.
public ilist<idictionary<string, string>> builddictionary<t>(hashset<t> sourceset, func<t, string> tokey, func<t, string> tomembervalue) { ilist<idictionary<string, string>> data = new list<idictionary<string, string>>(); foreach (var element in sourceset) { dictionary<string, string> newlookup = new dictionary<string, string>(); newlookup.add(tokey(element), $"{tokey(element)},{tomembervalue(element)}"); data.add(newlookup); } return data; } void main() { hashset<classa> setofas = new hashset<classa>(new[] { new classa { code = "foo", name = "bar" }, new classa { code = "foo2", name = "bar2" } }); hashset<classb> setofbs = new hashset<classb>(new[] { new classb { code = "foo", name = "bar" }, new classb { code = "foo2", name = "bar2" } }); var lookupofas = builddictionary(setofas, x => x.code, x => x.name); var lookupofbs = builddictionary(setofbs, x => x.code, x => x.name); } // define other methods , classes here public class classa { public string code { get; set; } public string name { get; set; } } public class classb { public string code { get; set; } public string name { get; set; } }
Comments
Post a Comment