详细代码实现c# 将list中(姓名,班级,小组,小组优先级,年龄,成绩)进行一级分类班级,二级分类小组进行分组并按照小组的优先级排序,展示归类分组后的数据,代码实现高效找出分组后的成绩匹配的值
时间: 2023-12-02 20:06:26 浏览: 69
以下是 C# 代码实现:
```csharp
// 定义学生类
public class Student
{
public string Name { get; set; }
public string Class { get; set; }
public string Group { get; set; }
public int GroupPriority { get; set; }
public int Age { get; set; }
public double Score { get; set; }
}
// 定义分组类
public class Group
{
public string Class { get; set; }
public string Name { get; set; }
public int Priority { get; set; }
public List<Student> Students { get; set; }
}
// 将学生列表按照班级、小组、小组优先级进行分组并排序
public List<Group> GroupStudents(List<Student> students)
{
var groups = new List<Group>();
var classGroups = students.GroupBy(s => s.Class);
foreach (var classGroup in classGroups)
{
var groupGroups = classGroup.GroupBy(s => s.Group);
foreach (var groupGroup in groupGroups)
{
var group = new Group
{
Class = classGroup.Key,
Name = groupGroup.Key,
Priority = groupGroup.First().GroupPriority,
Students = groupGroup.ToList()
};
groups.Add(group);
}
}
return groups.OrderBy(g => g.Priority).ToList();
}
// 显示分组后的数据
public void DisplayGroups(List<Group> groups)
{
foreach (var group in groups)
{
Console.WriteLine($"{group.Class} - {group.Name} (优先级: {group.Priority})");
foreach (var student in group.Students)
{
Console.WriteLine($" {student.Name} ({student.Age}岁, 成绩: {student.Score})");
}
}
}
// 在分组后的列表中查找成绩匹配的值
public double FindMatchingScore(List<Group> groups, double targetScore)
{
foreach (var group in groups)
{
var matchingStudent = group.Students.FirstOrDefault(s => s.Score == targetScore);
if (matchingStudent != null)
{
return matchingStudent.Score;
}
}
return -1; // 如果没有找到匹配的值,返回 -1
}
```
使用示例:
```csharp
var students = new List<Student>
{
new Student { Name = "张三", Class = "1班", Group = "A组", GroupPriority = 1, Age = 18, Score = 80 },
new Student { Name = "李四", Class = "1班", Group = "A组", GroupPriority = 1, Age = 19, Score = 85 },
new Student { Name = "王五", Class = "1班", Group = "B组", GroupPriority = 2, Age = 20, Score = 90 },
new Student { Name = "赵六", Class = "2班", Group = "C组", GroupPriority = 3, Age = 21, Score = 95 }
};
var groups = GroupStudents(students);
DisplayGroups(groups);
var matchingScore = FindMatchingScore(groups, 90);
Console.WriteLine($"匹配成绩: {matchingScore}"); // 输出 匹配成绩: 90
```
输出结果:
```
1班 - A组 (优先级: 1)
张三 (18岁, 成绩: 80)
李四 (19岁, 成绩: 85)
1班 - B组 (优先级: 2)
王五 (20岁, 成绩: 90)
2班 - C组 (优先级: 3)
赵六 (21岁, 成绩: 95)
匹配成绩: 90
```
阅读全文