LINQ tip: How to Implement group nesting by calling GroupBy multiple times

Source: Internet
Author: User

[Csharp]
Using System;
Using System. Linq;
 
Namespace ConsoleApplication1
{
Class Program
{
Public class S
{
Public int Year;
Public int Month;
Public int Day;
}

Static void Main (string [] args)
{
Var m = new [] {
New S {Year = 2000, Month = 1, Day = 10 },
New S {Year = 2000, Month = 2, Day = 10 },
New S {Year = 2010, Month = 1, Day = 1 },
New S {Year = 2010, Month = 2, Day = 1 },
New S {Year = 2010, Month = 1, Day = 2 },
New S {Year = 2010, Month = 2, Day = 2 },
New S {Year = 2000, Month = 1, Day = 2 },
New S {Year = 2000, Month = 2, Day = 2 },
};
 
Var q2 =
From s in m
Group s by s. Year into YearGroup
Select new
{
Year = YearGroup. Key,
MonthGroups =
From s2 in YearGroup
Group s2 by s2.Month into MonthGroup
Select new
{
Month = MonthGroup. Key,
Days =
From s3 in MonthGroup
Orderby s3.Day
Select s3.Day
}
};
 
 
Var q = m. GroupBy (
S => s. Year,
(Year, YearGroup) => new
{
Year,
MonthGroups =
YearGroup. GroupBy (
S2 => s2.Month,
(Month, MonthGroup) => new
{
Month,
Days = MonthGroup. OrderBy (s3 => s3.Day). Select (s3 => s3.Day)
}
)
}
);
 
Foreach (var elem in q)
// Foreach (var elem in q2)
{
Console. WriteLine ("Year = {0}", elem. Year );
Foreach (var elem2 in elem. MonthGroups)
{
Console. WriteLine ("\ tMonth = {0}", elem2.Month );
Foreach (var day in elem2.Days)
Console. WriteLine ("\ t \ tDay = {0}", day );
} Www.2cto.com
}
}
}
}
// Year = 2000
// Month = 1
// Day = 2
// Day = 10
// Month = 2
// Day = 2
// Day = 10
// Year = 2010
// Month = 1
// Day = 1
// Day = 2
// Month = 2
// Day = 1
// Day = 2
Author: zwvista

Related Article

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.