C# Method to take list of types with same property -
i have few different types mutual property:
public class { public int somecommonproperty { get; set; } /* * other stuff */ } public class b { public int somecommonproperty { get; set; } /* * other stuff */ }
i want have method takes list of of these objects property can iterate through list , compare property parameter like:
public static list<t> methodtotakelistofabovetypes<t>(this list<t> destinationlist, list<t> sourcelist, string someprop) { if (sourcelist != null && sourcelist.exists(tab => tab.somecommonproperty == someprop)) { destinationlist = sourcelist.where(tab => tab.somecommonproperty == someprop).tolist(); } homecoming destinationlist; }
the above code not work t not have definition of "somecommonproperty", makes sense. want pass more generic object property dont have create same method each type. cannot syntax right. create sense?
i know should set somecommonproperty field in base of operations class , inherit, doesn't seem work either reason.
make classes implement interface (or inherit property base of operations class), e.g.
public interface icommoninterface { int somecommonproperty { get; set; } }
then can set interface/class constraint on generic parameter type:
public static list<t> methodtotakelistofabovetypes<t>( list<t> destinationlist, list<t> sourcelist, string someprop) t: icommoninterface { // ... }
note: can avoid checking if item someprop exist in source (in worst case have enumerate sourcelist twice). filtering , check if there results
public static list<t> methodtotakelistofabovetypes<t>( list<t> destinationlist, list<t> sourcelist, string someprop) t: icommoninterface { if (sourcelist == null) homecoming destinationlist; var filtered = sourcelist.where(s => s.somecommonproperty == someprop).tolist(); homecoming filtered.any() ? filtered : destinationlist; }
c# list
No comments:
Post a Comment