c# - LINQ ForEach 语句

标签 c# .net linq

我有一个结构:

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)

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

想法?

最佳答案

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() 方法。

关于c# - LINQ ForEach 语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9831508/

相关文章:

c# - Xamarin 上的 NLog 因 System.MissingMethodException : string. Split(char,System.StringSplitOptions) 而失败

c# - 什么时候应该调用 Page.Header.DataBind?

c# - 如何以错误级别退出函数

c# - 使用 .NET sslstream 了解服务器/代理/客户端证书

c# - WPF 可能与 where 子句绑定(bind)?

c# - 使用OLEDB数据提供程序读取excel文件

c# - Moq、抽象类和虚拟属性

.net - PowerShell 3 : Every Command Execution Results In "The type initializer [...] threw an exception" Error

c# - 有没有办法将不同的 keySelector 返回给一个 OrderBy?

c# - 如何修复 "The collection to which the Single aggregate is applied must be empty or contain exactly one item"InvalidOperationException?