LINQ ForEach Statement

本文关键字:Statement ForEach LINQ | 更新日期: 2023-09-27 18:28:55

我有一个结构:

struct Student
{
    string Name;
    int ClassesMissedToday;
}

我现在有一个结构的列表:

List<Student> Students = new List<Student>();

我如何在LINQ中说出以下内容:

Students.Add(new Student { Name = "Bob", ClassesMissedToday = 2 }) 
Students.Add(new Student { Name = "Bob", ClassesMissedToday = 0 }) 
Students.Add(new Student { Name = "Joe", ClassesMissedToday = 0 })
Students.Add(new Student { Name = "Bob", ClassesMissedToday = 1 })  

(伪代码)

foreach Student.Name in Students:
   Console.WriteLine("Total Classes Missed Total: {0}", ClassedMissedToday(count all of them)

我知道这对一些人来说是微不足道的,但出于某种原因,我似乎找不到任何有效的简化示例。

想法?

LINQ ForEach Statement

Sum()获取帮助:

int total = students.Sum(s => s.ClassesMissedToday);

此外,您可能会发现自C#3.0 以来更有用的集合初始化语法

var students = new List<Student>
{
    new Student { Name = "Bob", ClassesMissedToday = 2 },
    new Student { Name = "Bob", ClassesMissedToday = 0 },
    new Student { Name = "Joe", ClassesMissedToday = 0 },
    new Student { Name = "Bob", ClassesMissedToday = 1 }
};

这将执行相同的操作,因为将为正在初始化的集合的每个底层条目调用Add()方法。

要获得所有学生缺课的总数,可以使用Sum运算符。

var totalMissed = students.Sum(s => s.ClassesMissedToday);
Console.WriteLine(String.Format("Total classes missed for all students is {0}", totalMissed);

要获得按学生名称分组时错过的类的计数,可以使用GroupBySum操作以及匿名类型。

var totals = students.GroupBy(s => s.Name).Select(g => new { Name = g.Key, TotalMissed = g.Sum(s => s.ClassesMissedToday) });
foreach (var u in totals)
{
    Console.WriteLine(String.Format("Total classes missed today for {0} is {1}", u.Name, u.TotalMissed));
}

您的问题假设这里是使用ForEach运算符的合适位置。你的问题中有一个foreach循环

foreach Student.Name in Students:
   Console.WriteLine("Total Classes Missed Total: {0}", 
       ClassedMissedToday(count all of them)

但你真的想为每个学生写一行到控制台吗?你似乎只是想要

Console.WriteLine("Total Classes Missed Total: {0}", 
    ClassedMissedToday(count all of them)

而你却在问:"我该如何总结错过的课程?"。

您可以使用许多LINQ运算符来实现这一点,包括ForEach运算符(如Will Marcouiller的回答所示),但您希望使用正确的工具来实现。这里的正确工具是Sum运算符。

Console.WriteLine("Total Classes Missed Total: {0}", 
    ClassedMissedToday(Students.Sum(s => s.ClassesMissedToday))
int missed;
Students.ForEach(s => missed += s.ClassedMissedToday);
Console.WriteLine("Total : {0}", missed);

你的问题似乎很奇怪。你确定只想把所有学生错过的总天数加起来吗?看看你的伪代码,你似乎是想写下那个学生错过的日子。如果是…

如果你按照学生的名字分组,你只会把每个名字都查一遍。

这是我的想法,所以它可能包含一个打字错误。它也不漂亮。。。

Students.GroupBy(student => student.Name)
.Select(filtered => new object { Name = filtered.Name, Missed = filtered.Sum(groups => groups.ClassesMissedToday) })
.ToList()
.ForEach(s => Console.WriteLine(string.Format("{0} has missed {1} classes", s.Name, s.Missed)));

这就是你想要实现的吗?