gpt4 book ai didi

c# - C#中自定义rank函数的优化

转载 作者:行者123 更新时间:2023-12-04 13:34:57 24 4
gpt4 key购买 nike

我写了学生课的代码到排名 他们根据他们的标记。代码工作准确,结果如下

Name:B  Marks:30    Rank:1
Name:C Marks:30 Rank:1
Name:A Marks:20 Rank:3
Name:D Marks:10 Rank:4
但我需要对其进行优化,以便处理它不会花费太多时间。下面是代码
public List<Students> GetRanks(List<Students> students)
{
List<Students> rStudents = new List<Students>();
students = students.OrderByDescending(a => a.marks).ToList();
for (int i = 0; i < students.Count; i++)
{
Students stu = new Students();
stu.Id = students[i].Id;
stu.Name = students[i].Name;
stu.marks = students[i].marks;

if (i > 0 && students[i].marks == students[i - 1].marks)
{
stu.rank = rStudents.Select(a => a.rank).LastOrDefault();
}
else
{
stu.rank = i + 1;
}
rStudents.Add(stu);
}
return rStudents;
}

List<Students> students = new List<Students>() {
new Students() { Id = 1, Name = "A", marks = 20 },
new Students() { Id = 1, Name = "B", marks = 30 },
new Students() { Id = 1, Name = "C", marks = 30 },
new Students() { Id = 1, Name = "D", marks = 10 },
};

List<Students> rStudents = GetRanks(students);


public class Students
{
public int Id { get; set; }
public string Name { get; set; }
public double marks { get; set; }
public int rank { get; set; }
}


foreach (Students s in GetRanks(students))
{
Console.WriteLine($"Name:{s.Name}\tMarks:{s.marks}\tRank:{s.rank}");
}

最佳答案

删除不必要的资源。并使用 产量会对大数据的性能产生影响。更少的行和更多的可读性。
如果您从 获取数据数据库更好的主意是在那里对它们进行排序然后获取它们。

  public static IEnumerable<Students> GetRanks(List<Students> students)
{
List<Students> rStudents = students.OrderByDescending(a => a.marks).ToList();
for (int i = 0; i < rStudents.Count; i++)
{
if (i > 0 && rStudents[i].marks == rStudents[i - 1].marks)
{
rStudents[i].rank = rStudents[i - 1].rank;
}
else
{
rStudents[i].rank = i + 1;
}
yield return rStudents[i];
}
}

关于c# - C#中自定义rank函数的优化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62750228/

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