0

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 个学生对象 Student[] stud = new Student[10]

如果 stud[0] 有 2 项费用( Fee[2] )并且他们是

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

如果 stud[1] 有 1 笔费用( Fee[2] )并且他们是

FeeID=1, FeeAmount=9.99

如果 stud[2] 有 3 项费用( Fee[3] )并且它们是

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

我需要按 TotalAmount(Fee Collection) 对学生收藏进行排序

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
4

5 回答 5

3

听起来你只是想要:

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

一定要爱 LINQ :)

有几点需要注意:

  • 这仍然只会计算每个学生一次的费用总和
  • 这目前不会处理空元素。你需要吗?(你似乎有一个固定的数组大小......也许List<Student>改用?)
  • 除非你之后真的需要它作为一个数组,否则只需挂断ToArray电话。请注意,除非您使用或虽然,否则每次迭代它都会对其进行排序。ToArrayToList
于 2013-03-12T22:22:23.173 回答
2
var results = stud.OrderByDescending(s => s.Fees.Sum(f => f.FeeAmount)).ToArray();
于 2013-03-12T22:22:54.653 回答
0

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

stud =
    (from s in stud
     orderby s.Fees.Sum(f => f.FeeAmount)
     select s)
    .ToArray();
于 2013-03-12T22:23:17.750 回答
0
var students = new List<Student>() { .. add students here ... };
students.OrderBy(x => x.Fees.Sum(y => y.FeeAmount));
于 2013-03-12T22:24:00.130 回答
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();

林克更好...

于 2013-03-12T22:40:24.343 回答