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



Will you give this article a +1 ? Thanks in advance




About The Author

Suprotim Agarwal, ASP.NET Architecture MVP works as an Architect Consultant and provides consultancy on how to design and develop Web applications.

Suprotim is also the founder and primary contributor to DevCurry, DotNetCurry and SQLServerCurry. He has also written an EBook 51 Recipes using jQuery with ASP.NET Controls.

Follow him on twitter @suprotimagarwal

comments

6 Responses to "GroupBy Multiple Values in LINQ"
  1. Busca Mexico said...
    December 20, 2009 at 2:52 PM

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

  2. Marin said...
    July 3, 2010 at 12:12 PM

    Thanks. Best article containing GroupBy in whole internet ;)

  3. João Cruz said...
    August 27, 2010 at 4:42 AM

    Thanks!!! Obrigado!!!

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

    best regards

  4. kim said...
    October 7, 2010 at 2:26 AM

    Thanks! It was very helpful for me.

  5. Zain Shaikh said...
    December 30, 2010 at 5:01 AM

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

  6. PonchoVillaPolkaBand said...
    March 11, 2011 at 4:20 AM

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

 

Copyright © 2009-2014 All Rights Reserved for DevCurry.com by Suprotim Agarwal | Terms and Conditions