2012-08-23 42 views
0

您好,我正在努力研究如何将物品分组到每个月的第一个和第二个半月以获得特定的年份和月份?c#linq组由两周或x天数?

例如说我必须列出在每月6日,每月15日项的名称。

说,比如我有

Flight Name   Flight Date 

Flight 1    01/07/2012 

Flight 2    12/07/2012 

Flight 3    18/07/2012 

Flight 4    28/07/2012 

我怎么会拆呢,所以我想在一年内由两星期组航班/月

的航班,每周七月1和2 - 2012年

7月第3周的航班和4 - 2012

所以这是我迄今为止.. 最终还是必须要使用某种视图模型的automapper等我不知道作为然而它会如何获取整齐地变成某种形式的视图模型的...

var flightEntities = from f in flightsAsViewModels 
          select new 
          { 
           YearGroups = from flightYearGroup in context.Flights 
           group flightYearGroup by flightYearGroup.FlightDateTime.Year 
           into yearGroup 
           orderby yearGroup.Key descending 
           select new 
           { 
            Year = yearGroup.Key, 
            MonthGroups = from flightMonthGroup in yearGroup 
                group flightMonthGroup by flightMonthGroup.FlightDateTime.Month 
                into monthGroup 
                orderby monthGroup.Key ascending 
                select new { 
                 Month = monthGroup.Key, 
                 HalfMonthGroups = from months in monthGroup 
                     group months by (months.FlightDateTime.Day <= 15 ? 1 : 2) into splitMonthFlights 
                     orderby splitMonthFlights.Key 
                     select new { WhichHalfOfMonth = splitMonthFlights.Key, Flights = splitMonthFlights } 
                } 

           } 
          }; 
+0

第5周呢?几乎每个月都有超过4周的时间。 –

+0

这是在LINQ to SQL(等)或LINQ to Objects? (LINQ to Objects会使它简单得多......) –

+0

@JonSkeet:根据标签,它是LINQ到SQL –

回答

0

在此,我贴的LINQ代码的要求。但不确定,这仍然可以用最短的方式实现。如果有,请告诉我。

var monthGroupedDates = from d in dates 
          group d by d.Month into fd 
          select new { Month = fd.Key, Dates = fd }; 

     foreach (var g in monthGroupedDates) 
     { 
      var groupByHalf = from n in g.Dates 
           group n by (n.Day <= 15 ? 1 : 2) into gd 
           orderby gd.Key 
           select new { WhichHalf = gd.Key, Dates = gd }; 
      foreach (var gh in groupByHalf) 
      { 
       string printString = (gh.WhichHalf == 1 ? "First" : "Second") + " week dates are:"; 
       foreach (var h in gh.Dates) 
       { 
        printString += h.ToString("dd/MM/yyyy") + ";"; 
       } 
       Console.WriteLine(printString); 
      } 

     } 

请注意,日期是您的要求中提到的日期之一。如果使用SQL的Linq,这可能需要稍微改动。

拉杰