在另一个集合的总和内和之前对集合进行排序

时间:2013-03-12 22:20:25

标签: c# sorting collections

2个班级

   public class Student
    {
        public int StudentID { get; set;}
        public string Name { get; set;}
        public List<Fee> Fees {get;set;}
    }

    public class Fee
    {
        public int FeeID { get; set;}
        public decimal FeeAmount { get; set; }
    }

假设有10个学生对象学生[] stud = new Student [10]

如果stud [0]有2笔费用(费用[2])且

FeeID=1, FeeAmount=54.23
FeeID=2, FeeAmount=234.98

如果专栏[1]有1个费用(费用[2]),他们是

FeeID=1, FeeAmount=9.99

如果专栏[2]有3笔费用(费用[3]),他们是

FeeID=1, FeeAmount=123.45
FeeID=2, FeeAmount=67.89
FeeID=3, FeeAmount=987.65

我需要通过TotalAmount(费用收取)对学生收藏进行排序

TotalAmount of Fee 
stud[0] = 54.23+234.98=289.21
stud[1] = =9,99
stud[2] = 123.45+67.89+987.65=1178.99

在排序后应该变成

stud[0] = 123.45+67.89+987.65=1178.99
stud[1] = 54.23+234.98=289.21
stud[2] = =9,99

5 个答案:

答案 0 :(得分:3)

听起来你只是想要:

stud = stud.OrderByDescending(x => x.Fees.Sum(fee => fee.FeeAmount)).ToArray();

得爱LINQ:)

有几点需要注意:

  • 这仍然只计算每位学生一次的费用总和
  • 这将 not 当前处理null元素。你需要吗? (你似乎有一个固定的数组大小...也许使用List<Student>代替?)
  • 除非你事后需要它作为一个数组,否则只需删除ToArray电话。请注意,除非您使用ToArrayToList,否则每次迭代它都会 对其进行排序。

答案 1 :(得分:2)

var results = stud.OrderByDescending(s => s.Fees.Sum(f => f.FeeAmount)).ToArray();

答案 2 :(得分:0)

一个简单的Linq查询应该完成这项工作:

stud =
    (from s in stud
     orderby s.Fees.Sum(f => f.FeeAmount)
     select s)
    .ToArray();

答案 3 :(得分:0)

var students = new List<Student>() { .. add students here ... };
students.OrderBy(x => x.Fees.Sum(y => y.FeeAmount));

答案 4 :(得分:0)

如果您使用旧的.net框架(没有Linq):

public class Student : IComparable
{
    public int StudentID { get; set; }
    public string Name { get; set; }
    public List<Fee> Fees { get; set; }

    private decimal TotalAmount
    {
        get
        {
            decimal total = 0;
            if (Fees != null)
                foreach (var fee in Fees)
                    total += fee.FeeAmount;
            return total;
        }
    }

    public int CompareTo(object obj)
    {
        //Ascending
        //return TotalAmount.CompareTo((obj as Student).TotalAmount);

        //Descending
        return (obj as Student).TotalAmount.CompareTo(TotalAmount);
    }
}

public class Fee
{
    public int FeeID { get; set; }
    public decimal FeeAmount { get; set; }
}


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

Linq更好......