我在使用这个 linq 查询时遇到了一些麻烦:
我有一个列表 ( allStats
),其中包含数据(请参阅allItems
类),该列表包含来自不同日期的多个条目,我需要对其进行分解,因此它们按月份和周数分隔,如下所示:
MonthNumber: 1,
List<Weeks> Weeks:
WeekNumber: 1,
List<Days> Days:
PunchedInLate: true,
PunchedOutLate: false,
PunchInDate: 2013-1-1 08:20:10,
PunchOutDate: 2013-1-1 15:00:00
PunchedInLate: true,
PunchedOutLate: false,
PunchInDate: 2013-1-2 08:20:10,
PunchOutDate: 2013-1-2 15:00:00
...
PunchedInLate: true,
PunchedOutLate: false,
PunchInDate: 2013-1-5 08:20:10,
PunchOutDate: 2013-1-5 15:00:00
MonthNumber: 1,
List<Weeks> Weeks:
WeekNumber: 2,
List<Days> Days:
PunchedInLate: true,
PunchedOutLate: false,
PunchInDate: 2013-1-10 08:20:10,
PunchOutDate: 2013-1-10 15:00:00
PunchedInLate: true,
PunchedOutLate: false,
PunchInDate: 2013-1-12 08:20:10,
PunchOutDate: 2013-1-12 15:00:00
PasteBin - 在这里你可以下载一个示例程序,这样你就可以在你的机器上运行它
它本质上是我试图创建的这个问题的答案的插件: SO - 将列表的部分拆分为 2 个列表并加入这 2 个
编辑:对不起,我忘了提到我在最后尝试了 .ToList() 方法,而不是在开始时进行强制转换,这会产生此错误:
Cannot implicitly convert type 'System.Collections.Generic.List<System.Collections.Generic.IEnumerable<TestClass.Weeks>>' to 'System.Collections.Generic.List<TestClass.Weeks>'
public class allItems
{
public DateTime PunchInDate { get; set; }
public DateTime PunchOutDate { get; set; }
public DayOfWeek DayOfWeek { get; set; }
public int WeekNumber { get; set; }
public int MonthNumber { get; set; }
public bool PunchedInLate { get; set; }
public bool PunchedOutLate { get; set; }
}
public class Months
{
public int MonthNumber { get; set; }
public List<Weeks> Weeks { get; set; }
}
public class Weeks
{
public int WeekNumber { get; set; }
public List<Days> Days { get; set; }
}
public class Days
{
public bool PunchedInLate { get; set; }
public bool PunchedOutLate { get; set; }
public DateTime PunchInDate { get; set; }
public DateTime PunchOutDate { get; set; }
public DayOfWeek DayOfWeek { get; set; }
}
和代码:
List<allItems> allStats = getAllStats(userId);
List<Months> stats = new List<Months>();
var asItems =
from item in allStats
group item by new { month = item.MonthNumber } into Month
select new Months()
{
MonthNumber = Month.Key.month,
Weeks = Month.Select(week =>
from weeks in allStats
group weeks by new { week = weeks.WeekNumber } into Week
select new Weeks()
{
//WeekNumber = week.WeekNumber,
WeekNumber = Week.Key.week, // I just noticed that I guess that I
// need this here, so I can group the
Days = Month.Select(days => // days correctly, right?
new Days()
{
PunchedInLate = days.PunchedInLate,
PunchedOutLate = days.PunchedOutLate,
DayOfWeek = days.DayOfWeek,
PunchInDate = days.PunchInDate,
PunchOutDate = days.PunchOutDate
}).ToList()
}).ToList()
};
List<Months> stat = asItems.ToList();