Http://u.115.com/file/f27504ff61 demo
You can use the group clause to group results by the specified key. For example, you can specify that results should be grouped by city so that all customers in London or Paris are in their respective groups. In this example, customer. City is the key.
NorthwindDataContext db = new NorthwindDataContext(); var AllCustomers = from Customer in db.Customers group Customer by Customer.City; foreach (var CustomerGroup in AllCustomers) { Console.WriteLine("---------------------"); Console.WriteLine("City : {0}", CustomerGroup.Key); foreach (var Customer in CustomerGroup) { Console.WriteLine("Customer Name : {0}", Customer.ContactName); } } NorthwindDataContext db = new NorthwindDataContext();var AllCustomers = from Customer in db.Customers group Customer by Customer.City;foreach (var CustomerGroup in AllCustomers){ Console.WriteLine("---------------------"); Console.WriteLine("City : {0}", CustomerGroup.Key); foreach (var Customer in CustomerGroup) { Console.WriteLine("Customer Name : {0}", Customer.ContactName); }}
When the Group clause is used to end the query, the results are in the list form. Each element in the list is an object with a key member and a list of elements grouped by the key. You must use a nested foreach loop to generate a group sequence query. The External Loop is used to access each group cyclically, and the internal loop is used to access members of each group cyclically.
If you must reference the results of a group operation, you can use the into keyword to create an identifier that can be further queried. The following query returns only groups of customers with more than two types:
NorthwindDataContext db = new NorthwindDataContext(); var AllCustomers = from Customer in db.Customers group Customer by Customer.City into CustomerGroup where CustomerGroup.Count() > 2 orderby CustomerGroup.Key select CustomerGroup;