Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to group and count the number of occurence of item in comma delimited string

Tags:

c#

linq

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?

like image 996
user3851289 Avatar asked Oct 25 '25 02:10

user3851289


1 Answers

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..