2011-07-08 67 views
0

在回答這個問題的更好的辦法:寫這個LINQ查詢P t2中

Better way to write this linq query?

我怎麼會建立以下在該線程相同模式的動態查詢?

例如,方法的簽名更改爲:

 public List<PeopleSearchList> GetPeople(string filter, string searchType, string searchOption) 
    { 

     return a new List of type PeopleSearchList 

    } 

所以現在我也不回「Firstnames」的單一陣列等我回到我的自定義類。

類是這樣的:

public class PeopleSearchList 
{ 
    public String IdentityCode { get; set; } 
    public String Firstname { get; set; } 
    public String Surname { get; set; } 
    public Int32 LoanCount { get; set; } 
    public String Group { get; set; } 

} 
+0

您可以使用[動態查詢庫](http://weblogs.asp.net/scottgu/archive/2008/01/07/dynamic-linq-part-1-using-the-linq-動態查詢library.aspx) – Magnus

回答

0

我的工作了。

只是想我會張貼解決方案讓別人看到。

public List<PeopleSearchList> GetPeople(string filter, string searchType, string searchOption) 
    { 
     IQueryable<Person> query = _context.People; 

     PropertyInfo property = typeof (Person).GetProperty(searchType); 
     MethodInfo method = typeof (string).GetMethod(searchOption, new[] {typeof (string)}); 

     query = query.Where(WhereExpression(property, method, filter)); 

     IQueryable<PeopleSearchList> resultQuery = query.Select(p => new PeopleSearchList 
                     { 
                      Firstname = p.Firstname, 
                      Group = p.Level.Year, 
                      IdentityCode = p.IdentityCode, 
                      LoanCount = p.Loans.Count(), 
                      Surname = p.Surname 
                     } 
      ).OrderBy(p => p.Surname); 

     return resultQuery.ToList(); 

    } 

Expression<Func<Person, bool>> WhereExpression(PropertyInfo property, MethodInfo method, string filter) 
    { 
     var param = Expression.Parameter(typeof(Person), "o"); 
     var propExpr = Expression.Property(param, property); 
     var methodExpr = Expression.Call(propExpr, method, Expression.Constant(filter)); 
     return Expression.Lambda<Func<Person, bool>>(methodExpr, param); 
    }