I have a Student class with the following properties
public class Student
{
public string Name{ get; set; }
public string Subject { get; set; }
}
Assume we have a list of students like below
var students = new List<Student>();
students.Add(new Student { Name = "John", Subject = "Math"});
students.Add(new Student { Name = "Bob", Subject = "English, Math"});
students.Add(new Student { Name = "Jane", Subject = "Math, History, Art"});
students.Add(new Student { Name = "Jim", Subject = "English"});
I want to group the students by subject and count the subject.
So the output would be
Math, 3
English, 1
History 1
Art 1
How can I achieve the outcome using linq?
students.SelectMany(arg => arg.Subject.Split(new []{','})) // split the Subject-property on commas
.Select(arg => arg.Trim()) // get rid of the whitespaces after commas
.GroupBy(arg => arg) // you can inject an equality comparer here, to achieve case insenstive grouping
.Select(arg => new
{
Subject = arg.Key,
Count = arg.Count()
}); // TODO output these objects to your console..
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