编程技巧:使用LINQ如何通过多次调用GroupBy实现分组嵌套
2012-07-12 07:20
701 查看
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); } } } } } //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
相关文章推荐
- LINQ技巧:如何通过多次调用GroupBy实现分组嵌套
- LINQ技巧:如何通过多次调用GroupBy实现分组嵌套
- LINQ实现多次调用GroupBy进行分组统计
- Android 通过WebService进行网络编程,使用工具类轻松实现
- 如何使用cocos的自动绑定工具实现lua调用c++的类
- 如何使用LINQ来简化编程
- 编程技巧:在Java应用开发中如何使用线程
- 编程技巧系列(6)如何使用MessageFormat格式化json串
- Android 通过WebService进行网络编程,使用工具类轻松实现
- 如何使用 AllowPartiallyTrustedCallers 属性来调用具有一个强名称从 Web 页通过使用 Visual C#.NET、 Visual C# 2005年或更高版本的程序集
- Android 通过WebService进行网络编程,使用工具类轻松实现
- 如何调用DLL (基于Visual C++6.0的DLL编程实现)
- JAVA编程技巧之如何实现HTTP的断点续传(原理篇)
- 在Android操作系统中如何使用Socket编程实现简易聊天室
- 想通过点击不同按钮实现不同jpanel类的调用,该如何实现?
- android如何使用BroadcastReceiver后台实现来电通话记录的监听并存取到sqllite数据库通过Contentprovilder实现接口
- vs2008 使用LINQ来简化编程的7个技巧
- linux下使用系统调用编程实现dir命令功能
- Android 通过WebService进行网络编程,使用工具类轻松实现
- 如何使用C语言实现递归调用