Introducing Radical.sh

Forget Code launches a powerful code generator for building API's

LINQ - Group by in C#

Example:
  1. using System;
  2. using System.Linq;
  3. using System.Xml.Linq;
  4.  
  5. namespace ForgetCode
  6. {
  7. public class MainClass
  8. {
  9. public static void Main()
  10. {
  11. dat customers = new dat(@"c:\data.mdf");
  12.  
  13. // queryCustomersByCity is an IEnumerable<IGrouping<string, Customer>>
  14. var queryCustomersByCity =
  15. from cust in customers
  16. group cust by cust.City;
  17.  
  18. // customerGroup is an IGrouping<string, Customer>
  19. foreach (var customerGroup in queryCustomersByCity)
  20. {
  21. Console.WriteLine(customerGroup.Key);
  22. foreach (Customer customer in customerGroup)
  23. {
  24. Console.WriteLine(" {0}", customer.Name);
  25. }
  26. }
  27. }
  28. }
  29. }