如何将OrderBy和OrderByDescending表达式组合成一个表达式?

时间:2013-11-14 06:27:19

标签: c#

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

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

现在我可以组合表达式但是如何表示desc&amp; 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; } }
  }

0 个答案:

没有答案