详细代码实现c# 将list中(姓名,班级,小组,小组优先级,年龄,成绩)进行一级分类班级,二级分类小组进行分组并按照小组的优先级排序,代码实现高效找出分组后的成绩匹配的值
时间: 2023-12-02 07:06:25 浏览: 97
以下是 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 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);
var matchingScore = FindMatchingScore(groups, 90);
Console.WriteLine(matchingScore); // 输出 90
```
阅读全文