c# - Entity Framework / Linq - Get distinct values of dynamically specified property -


i have requirement list of distinct values specific properties of collection of entities.

so, let's table has fields x, y, z, 1, 2, 3 x pk(thus off table).

i need unique values y, z, 1, 2, or 3, without knowing in method field i'm getting. pattern method be:

public list<objectname> getuniquefieldvalues(string fieldname) 

the "objectname" object object 2 properties, method above fill @ least 1 property per result.

someone in question had similar answer using parameterexpression , expression classes didn't provide enough information me specific task.

i tried reflection of course linq not within select expression.

i use if , call there ton of fields/properties in actual table/object it's impractical. save me little refactoring if base table ever changes.

sql version of i'm trying do:

select distinct [usersuppliedfieldname] tablename [someotherconditionsexist] 

pseudocode of have:

public list<returnobject> getuniquefieldvalues(int fkid, conditionobject searchmeta) {     using(dbentities db = new dbentities())     {         // getting basic set of results, notice "select *"         var results = f in db.table                       f.fkid == fkid && [some static conditions]                       select f;          // filtering initial results criteria in "searchmeta" object         results = applymoreconditions(results, searchmeta);          //  goal - select , return distinct field(s) specified in searchmeta.fieldname)      } } 

you might try (similar post suggested duplicate)

public static class dynamicquerier {     private delegate iqueryable<tresult> queryablemonad<tinput, tresult>(iqueryable<tinput> input, expression<func<tinput, tresult>> mapper);      public static iqueryable<tresult> select<tinput, tresult>(this iqueryable<tinput> input, string propertyname)     {         var property = typeof (tinput).getproperty(propertyname);         return createselector<tinput, tresult>(input, property, queryable.select);     }      private static iqueryable<tresult> createselector<tinput, tresult>(iqueryable<tinput> input, memberinfo property, queryablemonad<tinput, tresult> method)     {         var source = expression.parameter(typeof(tinput), "x");         expression propertyaccessor = expression.makememberaccess(source, property);         var expression = expression.lambda<func<tinput, tresult>>(propertyaccessor, source);         return method(input, expression);     } } 

for test, i've created dummy set of entities called tests, below query distinct values property2

var values = context.tests.select<test, int>("property2").distinct(); 

Comments

Popular posts from this blog

Detect support for Shoutcast ICY MP3 without navigator.userAgent in Firefox? -

web - SVG not rendering properly in Firefox -

java - JavaFX 2 slider labelFormatter not being used -