在另一个集合内并按其总和排序集合
本文关键字:集合 排序 另一个 | 更新日期: 2023-09-27 18:03:41
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 of Fee
stud[0] = 54.23+234.98=289.21
stud[1] = =9,99
stud[2] = 123.45+67.89+987.65=1178.99
for排序后应该变成
stud[0] = 123.45+67.89+987.65=1178.99
stud[1] = 54.23+234.98=289.21
stud[2] = =9,99
听起来你只是想:
stud = stud.OrderByDescending(x => x.Fees.Sum(fee => fee.FeeAmount)).ToArray();
爱上LINQ
有几点需要注意:
- 这仍然只计算每个学生一次的费用总和
- 这将不是当前处理null元素。你需要吗?(你似乎有一个固定的数组大小…也许用
List<Student>
代替?) - 除非你真的需要它作为一个数组之后,只是放弃
ToArray
调用。请注意,除非您使用ToArray
或ToList
,否则每次迭代时它都会对其进行排序。
var results = stud.OrderByDescending(s => s.Fees.Sum(f => f.FeeAmount)).ToArray();
一个简单的Linq查询就可以完成这项工作:
stud =
(from s in stud
orderby s.Fees.Sum(f => f.FeeAmount)
select s)
.ToArray();
var students = new List<Student>() { .. add students here ... };
students.OrderBy(x => x.Fees.Sum(y => y.FeeAmount));
如果你使用的是旧的。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();