gpt4 book ai didi

C# Linq 查询帮助删除 foreach 循环创建更清晰的代码

转载 作者:太空狗 更新时间:2023-10-30 01:01:13 25 4
gpt4 key购买 nike

有没有办法使用 linq 删除 for 循环来解决我遇到的问题

我想得到这个列表中每个学生和每个科目的科目和总分:

IEnumerable<Student> students = new List<Student> {
new Student() {Id = 1, Name = "John", Age = 13},
new Student() {Id = 2, Name = "Mary", Age = 12},
new Student() {Id = 3, Name = "Anne", Age = 14}
};

我有第二个列表,其中包含所有分数和主题信息:

IEnumerable<StudentScore> studentScores = new List<StudentScore> {
new StudentScore() {StudentId = 1, Subject = "Maths", Points = 54},
new StudentScore() {StudentId = 1, Subject = "Maths", Points = 32},
new StudentScore() {StudentId = 1, Subject = "English", Points = 55},
new StudentScore() {StudentId = 1, Subject = "English", Points = 54},

new StudentScore() {StudentId = 2, Subject = "Maths", Points = 44},
new StudentScore() {StudentId = 2, Subject = "Maths", Points = 37},
new StudentScore() {StudentId = 2, Subject = "English", Points = 59},
new StudentScore() {StudentId = 2, Subject = "English", Points = 64},

new StudentScore() {StudentId = 3, Subject = "Maths", Points = 53},
new StudentScore() {StudentId = 3, Subject = "Maths", Points = 72},
new StudentScore() {StudentId = 3, Subject = "English", Points = 54},
new StudentScore() {StudentId = 3, Subject = "English", Points = 59},
};

这是我想出的解决方案:

foreach (var student in students)
{
foreach (var studentScore in studentScores.Select(ss=>ss.Subject).Distinct())
{
Console.WriteLine("Name: " + student.Name + " Subject:" + studentScore + "Score: " + studentScores.Where(ss => ss.StudentId == student.Id)
.Where(ss => ss.Subject == studentScore)
.Sum(ss => ss.Points));
}
}

最佳答案

您的解决方案既有腰带又有背带 - foreach 循环与 LINQ 相结合,其中 LINQ 部分取决于您在 foreach 循环中通过的值.

了解如何完全使用 LINQ 完成此操作的诀窍是认识到 LINQ 处理的是表达式,而不是语句。因此,您需要一次生成整个列表,然后在单个 foreach 循环中打印它,或者使用 string.Format 方法来完全避免循环。

以下是您准备数据的方式:

var rows = students
.Join(
studentScores
, st => st.Id
, sc => sc.StudentId
, (st, sc) => new { Student = st, Score = sc }
)
.GroupBy(p => new { p.Student.Id, p.Score.Subject })
.Select(g => new {
Name = g.First().Student.Name
, Subj = g.Key.Subject
, Points = g.Sum(p => p.Score.Points)
})
.ToList();

现在您可以在 foreach 循环中执行此操作,并打印准备好的结果:

foreach (var r in rows) {
Console.WriteLine($"Name: {r.Name} Subject: {r.Subject} Score: {r.Score}");
}

关于C# Linq 查询帮助删除 foreach 循环创建更清晰的代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40632211/

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