【发布时间】:2009-09-27 22:05:32
【问题描述】:
我有一个 LINQ 查询,它试图获取表中所有日期的所有不同月份。
我使用 Distinct() 扩展方法进行了这项工作。然后我通过使用扩展方法提取月份使其更具可读性。然后它停止返回不同的结果。
谁能帮我弄清楚这里发生了什么?
顺便说一句,如果有人能告诉我获得不同月份的最佳方法,那也很好。但更重要的是我明白为什么会失败。
这是代码。
static class DcUtils
{
public static DateTime GetMonth(this Timesheet_Entry entry)
{
DateTime dt = new DateTime(
entry.Entry_Start_DateTime.Year,
entry.Entry_Start_DateTime.Month,
1
);
return dt;
}
}
public class Demo
{
public DemonstrateBug()
{
TimesheetDataClassesDataContext dc = new TimesheetDataClassesDataContext();
/////////////////////////////////
//// Here are the queries and their behaviours
var q1 = (
from ts
in dc.Timesheet_Entries
select new DateTime(ts.Entry_Start_DateTime.Year, ts.Entry_Start_DateTime.Month, 1)
).Distinct();
// This returns 3 (which is what I want)
int lengthQuery1 = q1.Count();
// And now for the bug!
var q2 = (
from ts
in dc.Timesheet_Entries
select ts.GetMonth()
).Distinct();
// This returns 236 (WTF?)
int lengthQuery2 = q2.Count();
}
}
【问题讨论】:
-
为什么您期望在第二个查询中得到不同的结果?你没有在任何地方打电话给
Distinct。 -
谢谢梅尔达德。这只是复制示例的问题。我现在已经在示例中添加了 distinct。
标签: linq linq-to-sql extension-methods