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






About The Author

Suprotim Agarwal
Suprotim Agarwal, Developer Technologies MVP (Microsoft Most Valuable Professional) is the founder and contributor for DevCurry, DotNetCurry and SQLServerCurry. He is the Chief Editor of a Developer Magazine called DNC Magazine. He has also authored two Books - 51 Recipes using jQuery with ASP.NET Controls. and The Absolutely Awesome jQuery CookBook.

Follow him on twitter @suprotimagarwal.

9 comments:

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!

Unknown 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?

Unknown said...

how to apply with a datatable, with dynamic columns

Johns said...

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