Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

LINQ ForEach Statement

Tags:

c#

.net

linq

I have a struct:

struct Student
{
    string Name;
    int ClassesMissedToday;
}

I now have a list for the struct:

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

How can I say the following in 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 })  

(pseudo code)

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

I know this is rather trivial to some, but for some reason I can't seem to find any valid example simplified.

Ideas?

like image 910
Rob Avatar asked Dec 03 '22 04:12

Rob


1 Answers

Sum() for the help:

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

Also you might find more useful collection initialization syntax since 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 }
};

This will do the same since would call Add() method for the each underlying entry of the collection being initialized.

like image 148
sll Avatar answered Dec 05 '22 17:12

sll