C # 3.0 Getting Started series (ix)-GROUPBY operations

Source: Internet
Author: User

A friend feedback that I provided the sample can not compile. Probably a version of the problem, you can go to http://msdn2.microsoft.com/en-us/bb330936.aspx download the for Beta1 version. This section goes on to talk about GroupBy.

In the previous section, we talked about how to understand the results of the groupby return. This section will be extended to explain this idea. Let's take a look at the following examples

Anonymous class for select in GroupBy operation

var q = from p in db.Products
group p by p.CategoryID into g
select new { CategoryID = g.Key, g };

In this example, the anonymous class is used in the select operation. For the first time in this series, the anonymous class is mentioned in the http://www.cnblogs.com/126/archive/2006/12/20/503519.html article. This article will once again explain the understanding of anonymous classes. The so-called anonymous class, its essence, is not anonymous, but the compiler to help you create such a class, in the eyes of users, as if not to create, this so-called anonymous class. That is, the compiler, at compile time, still has this class, which is created by the compiler itself and whose name is compiler-defined. In the anonymous class in the example above, there are 2 property, one called CategoryID, and one named G. It is to be noted that this anonymous class, in essence, has been repackaged for return results. And that property, called G, encapsulates a complete grouping. As shown, carefully compare the differences with the previous diagram.

If, use the following statement.

var q = from p in db.Products
group p by p.CategoryID into g
select new { CategoryID = g.Key,GroupSet = g };

Just rename G to Groupset. You need to use the following traversal to get each product record.

foreach (var gp in q)
{
 if (gp.CategoryID == 7)
 { 
  foreach (var p in gp.GroupSet)
  {

  }
 }
}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.