Here is an example of GroupBy . Say we have a simple class:
public class Person { public string Name { get; set; } public int Age { get; set; } public char Sex { get; set; } }
Then you can use GroupBy as follows:
var people = new List<Person> { new Person { Name = "Joe", Age = 30, Sex = 'M' }, new Person { Name = "Liz", Age = 22, Sex = 'F' }, new Person { Name = "Jim", Age = 22, Sex = 'M' }, new Person { Name = "Alice", Age = 30, Sex = 'F' }, new Person { Name = "Jenny", Age = 22, Sex = 'F' } }; var groups = people.GroupBy(p => p.Age); foreach (var group in groups) { foreach (var person in group) Console.WriteLine(person.Name + " - " + person.Age); }
Regarding grouping by several properties, see the following: http://weblogs.asp.net/zeeshanhirani/archive/2008/05/07/group-by-multiple-columns-in-linq-to-sql.aspx
LINQ TO DataSet: Multiple Data Table Groups
Basically, this is the same syntax with an anonymous type, for example:
var groups = people.GroupBy(p => new { p.Age, p.Sex });
Note that you can use multiple OrderBy s:
var query = people.OrderBy(p => p.Age).ThenBy(p => p.Sex);
Also note that the result of the last GroupBy statement and the result of this OrderBy statement are NOT the same.
Venemo
source share