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);


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
Suprotim Agarwal, ASP.NET Architecture MVP (Microsoft Most Valuable Professional) 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 is the Editor of a Developer Magazine called DNC Magazine. He has also written two EBooks 51 Recipes using jQuery with ASP.NET Controls. and The Absolutely Awesome jQuery CookBook

Follow him on twitter @suprotimagarwal


Busca Mexico said...

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

Marin said...

Thanks. Best article containing GroupBy in whole internet ;)

João Cruz said...

Thanks!!! Obrigado!!!

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

best regards

kim said...

Thanks! It was very helpful for me.

Zain Shaikh said...

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

PonchoVillaPolkaBand said...

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

Amir Chatrbahr said...

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?

Santiago Victorino said...

how to apply with a datatable, with dynamic columns