开发者

Sorting with Mathematical Formula with nHibernate (C#)

public class Feedback
{
 public virtual int Id { get; private set; }    
 public virtual string ContentText { get; set; }
 public virtual DateTime FeedbackDate { get; set; }
 public virtual Student student { get; set; }
}

My Feedback Class.

public class Student
{
 public virtual int Id { get; private set; }    
 public virtual int NumberOfStars { get; set; }
 public virtual IList<Feedback> Feedbacks { get; private set; }

 public Student()
 {
  Feedback = new List<Feedbacks>();
 }
}

My Student Class

public class Course
{
 public virtual int Id { get; set; }
    // bla bla bla
 public virtual IList<Student> Students { get; private set; }

 public Course()
 {
  Students = new List<Student>();
 }

 public IList<Student> SortBy(string type)
 {
  // some oth开发者_如何学Pythoner sorting
  else if (type.Equals("popular")){
   sortedStudents = session.CreateCriteria(typeof(Student))
    .CreateAlias("Student", "s")
    .CreateAlias("s.Feedback", "f")
    .AddOrder(Order.Desc( -------- ))
    .List();
  }

  return (IList<Student>) sortedStudents;
 }

}

My Course class

I want sort students in a Course with method SortBy : if type is x i will sort with following rule (Students.Feedback.Count)*5 + Student.NumberOfStars)

How ?


HQL:

List<Student> sortedStudents = session
  .CreateQuery(
    @"from Students student
      where student.Course == :course
      order by size(student.Feedbacks) * 3 + student.NumberOfStars")
  .SetEntity("course", course)
  .List<Student>();

size is a HQL function. See the chapter "Expressions" in the NH documentation.

You may also select it with Criteria and sort it with Linq.

Edit

Just saw that you use it in a property and you may have the students already in memory. You don't need a query, just to sort it.

return students
  .OrderBy(x => x.Feedback.Count * 5 + x.NumberOfStars)
  .ToList();


Query with LINQ

IList sortedStudents = (from student in this.Students
                        where student.Course == this
                        orderby (student.Feedbacks.Count*3 + student.NumberOfStars)
                        select student).ToList();
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜