GroupBy Multiple Values in LINQ

Here's a simple example to show you how to GroupBy Multiple Values using LINQ. In this example, I am grouping by Age and Sex to find the count of people who have the same age and sex

public partial classLINQ: System.Web.UI.Page
{
protected void Page_Load(objectsender, EventArgs e)
{
List<Employee> empList = newList<Employee>();
empList.Add(newEmployee(){ID = 1, FName = "John", Age = 23, Sex = 'M'});
empList.Add(newEmployee(){ID = 2, FName = "Mary", Age = 25, Sex = 'F' });
empList.Add(newEmployee(){ID = 3, FName = "Amber", Age = 23, Sex = 'M'});
empList.Add(newEmployee(){ID = 4, FName = "Kathy", Age = 25, Sex = 'M'});
empList.Add(newEmployee(){ID = 5, FName = "Lena", Age = 27, Sex = 'F' });
empList.Add(newEmployee(){ID = 6, FName = "Bill", Age = 28, Sex = 'M'});
empList.Add(newEmployee(){ID = 7, FName = "Celina", Age = 27, Sex = 'F' });
empList.Add(newEmployee(){ID = 8, FName = "John", Age = 28, Sex = 'M'});

var sums = empList
.GroupBy(x => new{ x.Age, x.Sex })
.Select(group => new{ Peo = group.Key, Count = group.Count() });

foreach (var employee insums)
{
Response.Write(employee.Count + ": "+ employee.Peo);
}

}
}

classEmployee
{
public int ID { get; set; }
public stringFName { get; set; }
public int Age { get; set; }
public charSex { get; set; }
}

You can also check out similar LINQ Tutorials over here

9 comments:

  1. finally an easy example in how to group by two or more columns! Thank you!!

    ReplyDelete
  2. Thanks. Best article containing GroupBy in whole internet ;)

    ReplyDelete
  3. Thanks!!! Obrigado!!!

    I had searched everywhere... and couldn't find a clear example of GroupBy... Marin said it all!

    best regards

    ReplyDelete
  4. Thanks! It was very helpful for me.

    ReplyDelete
  5. Good, nice post. Now I understand Group by properly, thanks :)

    ReplyDelete
  6. PonchoVillaPolkaBandMarch 11, 2011 at 4:20 AM

    Thanks Suprotim! Finally somebody who posts a simple explanation to a common question! Take the hint, Microsoft!

    ReplyDelete
  7. imagine you have this:
    var sums = empList
    .GroupBy(x => new{ x.Age, x.Sex });

    if you need to return 'sums' in your method, what would be the return type?

    ReplyDelete
  8. how to apply with a datatable, with dynamic columns

    ReplyDelete
  9. Hi Dear can you please help me to return the "sums" to the view.

    ReplyDelete