【发布时间】:2020-04-21 16:44:58
【问题描述】:
我需要在 C# 中使用同一对象类型中的 4 个不同属性来实现排序。
假设对象 Student 具有姓名、ID、生日和年级。我如何重用代码对它们中的每一个进行排序。我已经设法按名称排序,我如何重用代码?
private void btnSortName_Click(object sender, EventArgs e)
{
Student obj = new Student();
List<Student> listOfStudents = obj.List();
int student_count = listOfStudents.Count();
int first_index, last_index;
for (first_index = 1; first_index < student_count; first_index++)
{
last_index = first_index - 1;
Student first = listOfStudents[first_index];
Student last = listOfStudents[last_index];
while (last_index >= 0 && DateTime.Compare(last.RDate, first.RDate) > 0)
{
listOfStudents[last_index + 1] = listOfStudents[last_index];
last_index = last_index - 1;
}
listOfStudents[last_index + 1] = first;
}
DataTable dt = Utility.ConvertToDataTable(listOfStudents);
dataGridStudents.DataSource = dt;
btnSortName.Visible = false;
btnSortName.Enabled = false;
btnSortNameD.Visible = true;
btnSortNameD.Enabled = true;
}
我尝试通过创建插入排序方法并将属性作为参数传递并返回该对象的列表来执行此操作,但是这两个都显示错误:
public List<Student> insertion_Sort(ref String data, Boolean asc)
{
Student obj = new Student();
List<Student> listOfStudents = obj.List();
int student_count = listOfStudents.Count();
int first_index, last_index;
for (first_index = 1; first_index < student_count; first_index++)
{
last_index = first_index - 1;
Student first = listOfStudents[first_index];
Student last = listOfStudents[last_index];
if (asc){
while (last_index >= 0 && DateTime.Compare(last.data, first.data) > 0)
{
listOfStudents[last_index + 1] = listOfStudents[last_index];
last_index = last_index - 1;
}
listOfStudents[last_index + 1] = first;
}
else
{
while (last_index >= 0 && DateTime.Compare(last.data, first.data) < 0)
{
listOfStudents[last_index + 1] = listOfStudents[last_index];
last_index = last_index - 1;
}
listOfStudents[last_index + 1] = first;
}
}
return listOfStudents;
}
我该如何解决这些问题?
【问题讨论】:
-
也许你可以使用一个联合数据结构,它可以获取类的所有属性。然后在 insert_sort 方法开始时,创建两个变量,它们将采用相应对象的属性并将它们与
<和>进行比较,而不是仅适用于日期的日期时间比较(如果有,则将日期时间转换为刻度数其他问题)。但我觉得最好做个表格,学生属性作为行数据,然后按列排序。 -
您必须将
class Student和public List<Student> insertion_Sort方法访问修饰符调整为相同。class Student和insertion_Sort都应该具有相同的访问修饰符(如public或private或protected)
标签: c# oop methods modular-design