写这个linq查询Pt2的更好方法

时间:2011-07-08 13:50:17

标签: c# linq entity-framework

回答这个问题:

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; }

}

1 个答案:

答案 0 :(得分: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);
    }