1

如何将多个表达式组合成一个表达式并将其作为参数传递?

// how to combine order by expression???
Expression<Func<Student, dynamic>> orderby = o => o.Marks desc then o.Name; /* ??? */

现在我可以组合表达式,但是如何表示 desc 和 asc?我可以使用像 OrderBy().ThenBy().ThenByDescending() 这样的扩展方法 我怎样才能取出表达式?

class Program
  {
    static void Main(string[] args)
    {
      // this is the normal extension method way
      IEnumerable<Student> students = Student.All.Where(o => o.Marks > 50).OrderByDescending(o => o.Marks).ThenBy(o => o.Name).Skip(10).Take(10);

      // construct filter, and I can combine this kind of expression
      Expression<Func<Student, bool>> filter = o => o.Marks > 50;

      // but how to combine order by expression???
      Expression<Func<Student, dynamic>> orderby = o => o.Marks desc then o.Name; /* ??? */

      IEnumerable<Student> howtogetstudents = GetStudents(filter, orderby, 2, 10);
    }

    static IEnumerable<Student> GetStudents(Expression<Func<Student, bool>> filter,
      Expression<Func<Student, dynamic>> orderby, int pageNumber, int pageSize)
    {
      IQueryable<Student> students = Student.All;

      return students.Where(filter).OrderBy(orderby).Skip((pageNumber - 1) * pageSize).Take(pageSize);
    }
  }

  class Student
  {
    Student() { }

    public int Id { get; set; }
    public string Name { get; set; }
    public DateTime Birthday { get; set; }
    public decimal Marks { get; set; }

    public static IQueryable<Student> All { get { return null; } }
  }
4

0 回答 0