嗨,我想弄清楚如何将项目分组到每个月的第一个和第二个月的某一年和一个月?
即
比如说我必须在每个月的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
我将如何拆分它以便我想在一年/一个月内按星期一组航班
即
2012年7月第1周和第2周的航班
2012年7月3日和4日的航班
所以这就是我到目前为止所拥有的...... 最终它必须是某种使用automapper等的视图模型我还不确定它是如何将它整齐地融入某种ViewModel形式...
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 :(得分: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);
}
}
请注意,日期是您的要求中提到的日期。如果它的Linq with SQL,这可能需要稍作修改。
拉吉