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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With