将字段名称传递给linq查询

时间:2014-05-20 21:45:15

标签: c# linq linq-to-entities

在类似这样的方法中:

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
}

我已经将where子句中的字段名称硬编码为custom_field但是有一种方法可以将其作为参数传递给我的方法吗?例如,可能有a.custom_field , a.field2 , a.teahcer_id , etc....

2 个答案:

答案 0 :(得分:2)

您可以通过创建更高阶函数(请参阅Refactor methods - pass in property name)来完成此操作

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
}

答案 1 :(得分:1)

你可以使用这样的东西:

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

并称之为:

var result = GetEligibleTeachers(t => t.SomeField == "SomeValue");