【问题标题】:Is there anyway to sort a list based on difference of its two values?反正有没有根据两个值的差异对列表进行排序?
【发布时间】:2019-08-08 11:22:36
【问题描述】:

所以我有一个对象类型Student 的列表_students,每个Student 对象都有一个对象类型Courses 的列表Course。每个课程对象有两个字段“总课数”和“学生参加的课数”。我想通过两个属性的差异对这个列表与学生对象进行排序,这样参加过所有课程的人就会在列表的 0 索引处。

我尝试使用类似的东西,但不起作用。

_students.ForEach(c => c.Courses.OrderBy(le => le.Total - le.Attended))

【问题讨论】:

  • 现在您订购的是课程而不是学生,您只为每个学生订购。
  • 我的错,上面的课程是对象类型课程的列表
  • 请编辑您的问题并添加所有缺失的详细信息和代码。
  • 如果您包含您的父子列表的示例会有所帮助吗?

标签: c# list linq


【解决方案1】:

我认为你可以这样做:

List<Student> students = new List<Student>(); 

students.Sort(delegate(Student s1, Student s2) { 
    int s1remainingLectures = 0;
    int s2remainingLectures = 0;
    foreach(Course c in s1.Courses) s1remainingLectures += c.total - c.Attended ;
    foreach(Course c in s2.Courses) s2remainingLectures += c.total - c.Attended ;
    return s1remainingLectures.CompareTo(s2remainingLectures); });

【讨论】:

    【解决方案2】:

    Course 上实现IComparable

    这是另一个问题的通用示例:

    public class BankAccount : IComparable<BankAccount>
    {
        [...]
    
        public int CompareTo(BankAccount that)
        {
            return this.Balance.CompareTo(that.Balance);
        }
    }
    

    您可以将自己的逻辑放入 CompareTo 函数中。

    【讨论】:

      【解决方案3】:

      实际上,在您的查询中,您正在学生列表中循环并订购他们拥有的课程。

      如果我非常了解你,我认为你正在尝试做这样的事情:

       var orderedStudents=_students.ForEach(c => c.Courses.OrderBy(le => le.Total - le.Attended)).ToList();
      

      【讨论】:

        猜你喜欢
        • 2021-07-20
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-03-04
        • 2010-10-26
        • 2022-08-02
        • 1970-01-01
        • 2021-08-27
        相关资源
        最近更新 更多