0

In a method something like this:

public List<Teachers> GetEligibleTeachers(string fieldname)
{
  var query = from t in this.Context.Teachers
              // some more joins and logic , etc..
              where t.custom_field == true
 // .... rest of the query
}

I have hardcoded the name of the field in the where clause to custom_field but is there is a way I can pass that as a parameter to my method? so for example could have a.custom_field , a.field2 , a.teahcer_id , etc....

  • 2
    Not without reflection. Are you willing to go that far? – BradleyDotNET May 20 '14 at 21:46
  • You should look into [`Expression Trees`](http://msdn.microsoft.com/en-us/library/bb882637.aspx). You might find a [`Predicate Builder`](http://www.albahari.com/nutshell/predicatebuilder.aspx) to be of great use. – crthompson May 20 '14 at 21:51
  • You don't need reflection as long as you know the field name in the calling function – reggaeguitar May 20 '14 at 22:11
  • you can use a predicate for this – Gayot Fow May 20 '14 at 23:38
  • @GayotFow something like reggaeguitar answer? please read the comments I posted there. –  May 21 '14 at 00:34
  • @DevWannaBe, almost. But having said that, I think the design/strategy may be misconceived. If the 'where' clause cannot be resolved to an explicit condition given what's been provided in the linq projection, then it's the wrong tool for the job. Sorry..... – Gayot Fow May 21 '14 at 02:28

2 Answers2

2

You can do this by creating a higher ordered function (see Refactor methods - pass in property name) like this

public List<Teachers> GetTeachers()
{
    return GetEligibleTeachers(x => x.fieldname);
}

public List<Teachers> GetEligibleTeachers(Func<Teachers, bool> elementIdentity)
{
   var query = Context.Teachers.Where(elementIdentity == true) // rest of query
}
Community
  • 1
  • 1
reggaeguitar
  • 1,795
  • 1
  • 27
  • 48
  • 1
    one big problem: x.fieldname : fieldname is not a member of Teachers table. Notice I have a bunch of joins, it is on one of the other tables. –  May 20 '14 at 22:26
  • I guess you will need reflection or expression trees then, it's beyond my expertise – reggaeguitar May 20 '14 at 22:29
  • @DevWannaBe - If the joins are always the same, then just take a `Func` instead. – Bobson May 21 '14 at 15:58
1

You could work with something like this:

public List<Teachers> GetEligibleTeachers(Func<Teachers, bool> predicate)
{
  var query = this.Context.Teachers.Where(predicate);
 // .... rest of the query
}

And call it like this:

var result = GetEligibleTeachers(t => t.SomeField == "SomeValue");
DavidG
  • 113,891
  • 12
  • 217
  • 223