arjun
arjun

Reputation: 17

How to use Group by of two elements in an object and get the count in List?

I have a List(Student) where Student class is like

public class Student
{
    string Name;
    string Class;
    string Division;
}

I have an other class like StudentCount.

public class StudentCount
{
    string Class;
    string Division;
    string Count;
}

I have to populate the List(StudentCount) from List(Student).

SQL statement for above result

select Class,division,count(*) 
from Student
group by Class, Division

Students Data

Name - Class - Division

Aa   -   1    -   A

Bc   -   1    -   A

Cc    -  1   -    B

Dd   -   2    -   A

I am looking for a result like

Expected Result

Class - Division - Count

1    -    A     -    2

1 -       B       -  1

2  -      A   -      1

I have the student data in a List (Student). I have to get the result in List (StudentCount)

Can anyone help to achieve the result through in C#?

Upvotes: 0

Views: 147

Answers (3)

Hossein Narimani Rad
Hossein Narimani Rad

Reputation: 32481

First make your class members public (However its not recommended to have public fields in the class). Like this:

public class Student
{
    public string Name;
    public string Class;
    public string Division;
}

Then use this:

 var groups = data.GroupBy(item => new { item.Class, item.Division })
                  .Select(item => new StudentCount()
                  {
                      Class = item.Key.Class,
                      Division = item.Key.Division,
                      Count = item.Count().ToString() //the Count is of type string, so don't forget to make the proper conversion
                  });

Upvotes: 1

spender
spender

Reputation: 120400

Assuming you promote your internal fields to public properties, I believe the following Linq query fulfills your requirements.

students
    .GroupBy(s => new{s.Class, s.Division})
    .Select(g => new StudentCount{Count = g.Count(),
                                  Class = g.Key.Class, 
                                  Divison = g.Key.Division})

Upvotes: 3

Ufuk Hacıoğulları
Ufuk Hacıoğulları

Reputation: 38468

You can use an anonymous object for grouping:

var groups = data.GroupBy(item => new { item.Class, item.Division });
                 .Select(item => new StudentCount 
                                     { 
                                         Class = item.Key.Class, 
                                         Division = item.Key.Divison,
                                         Count = item.Count()
                                     });

Upvotes: 2

Related Questions