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
Tweet
9 comments:
finally an easy example in how to group by two or more columns! Thank you!!
Thanks. Best article containing GroupBy in whole internet ;)
Thanks!!! Obrigado!!!
I had searched everywhere... and couldn't find a clear example of GroupBy... Marin said it all!
best regards
Thanks! It was very helpful for me.
Good, nice post. Now I understand Group by properly, thanks :)
Thanks Suprotim! Finally somebody who posts a simple explanation to a common question! Take the hint, Microsoft!
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?
how to apply with a datatable, with dynamic columns
Hi Dear can you please help me to return the "sums" to the view.
Post a Comment