gpt4 book ai didi

c# - 在另一个对象集合中对对象集合进行排序

转载 作者:行者123 更新时间:2023-11-30 15:35:06 24 4
gpt4 key购买 nike

首先我有 2 个类

class Student
{
int StudentID
string Name
Fee fee
}
class Fees
{
int FeeID
string FeeName
DateTime FeeDueDate
}

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

如果 stud[0] 有 4 个费用 ( Fee[4] ) 并且它们是

FeeID=1, FeeName="Books", FeeDueDate="2014/06/25"
FeeID=2, FeeName="Tuition", FeeDueDate="2013/03/21"
FeeID=3, FeeName="Sports Equipment", FeeDueDate="2013/03/18"
FeeID=4, FeeName="School Dorm", FeeDueDate="2013/07/26"

而 stud[1] 有 2 笔费用 ( Fee[2] ) 而他们是

FeeID=2, FeeName="Books", FeeDueDate="2014/06/20"
FeeID=4, FeeName="School Dorm", FeeDueDate="2013/03/26"

stud[2] 有……

我需要按 FeeDueDate 升序对第二个集合进行排序,同时保持学生的相同顺序

所以排序之后就是

stud[0] =>

FeeID=3, FeeName="Sports Equipment", FeeDueDate="2013/03/18"
FeeID=2, FeeName="Tuition", FeeDueDate="2013/03/21"
FeeID=4, FeeName="School Dorm", FeeDueDate="2013/07/26"
FeeID=1, FeeName="Books", FeeDueDate="2014/06/25"

stud[1] =>

FeeID=4, FeeName="School Dorm", FeeDueDate="2013/03/26"
FeeID=2, FeeName="Books", FeeDueDate="2014/06/20"

如何做到这一点?谢谢

这张图片还显示了我的对象集合 http://oi50.tinypic.com/wuq9o3.jpg

最佳答案

假设你的类是这样的:

   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 string FeeName { get; set;}
public DateTime FeeDueDate { get; set; }
}

你可以这样做:

        Student[] studs = new Student[10]

//somehow fill the array

foreach (var student in studs)
{
student.Fees = student.Fees.OrderBy(c => c.FeeDueDate).ToList()
}

编辑为确保 Fees 列表不为空,您可以像这样初始化它:

   public class Student
{
public Student()
{
Fees = new List<Fees>();
}

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

关于c# - 在另一个对象集合中对对象集合进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15372481/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com