GroupBy in LINQ Archives - Anuj Varma, Hands-On Technology Architect, Clean Air Activist https://www.anujvarma.com/tag/groupby-in-linq/ Production Grade Technical Solutions | Data Encryption and Public Cloud Expert Thu, 14 Jan 2016 13:40:39 +0000 en-US hourly 1 https://wordpress.org/?v=6.9.4 https://www.anujvarma.com/wp-content/uploads/anujtech.png GroupBy in LINQ Archives - Anuj Varma, Hands-On Technology Architect, Clean Air Activist https://www.anujvarma.com/tag/groupby-in-linq/ 32 32 GroupBy in LINQ https://www.anujvarma.com/groupby-in-linq/ https://www.anujvarma.com/groupby-in-linq/#respond Thu, 14 Jan 2016 13:40:39 +0000 http://www.anujvarma.com/?p=3780 The group clause enables you to group your results based on a key that you specify. For example you could specify that the results should be grouped by the City […]

The post GroupBy in LINQ appeared first on Anuj Varma, Hands-On Technology Architect, Clean Air Activist.

]]>
The group clause enables you to group your results based on a key that you specify. For example you could specify that the results should be grouped by the City so that all customers from London or Paris are in individual groups. In this case, cust.City is the key.

When you end a query with a group clause, your results take the form of a list of lists. Each element in the list is an object that has a Key member and a list of elements that are grouped under that key. When you iterate over a query that produces a sequence of groups, you must use a nestedforeach loop. The outer loop iterates over each group, and the inner loop iterates over each group’s members.

// queryCustomersByCity is an IEnumerable<IGrouping<string, Customer>>
  var queryCustomersByCity =
      from cust in customers
      group cust by cust.City;

  // customerGroup is an IGrouping<string, Customer>
  foreach (var customerGroup in queryCustomersByCity)
  {
      Console.WriteLine(customerGroup.Key);
      foreach (Customer customer in customerGroup)
      {
          Console.WriteLine("    {0}", customer.Name);
      }
  }

The post GroupBy in LINQ appeared first on Anuj Varma, Hands-On Technology Architect, Clean Air Activist.

]]>
https://www.anujvarma.com/groupby-in-linq/feed/ 0