如何将日期时间变量与 lambda 表达式进行比较

本文关键字:表达式 lambda 比较 变量 日期 时间 | 更新日期: 2023-09-27 18:37:11

具有日期引用UserJoinDate和日期列表 列出朋友已加入 我想计算在UserJoinDate之前有多少朋友加入服务,以及有多少朋友在同一时间或之后加入服务。

我写了以下几行,但它不起作用:

List<DateTime> joinersDates = getJoinersDates();
FriendsJoinedBeforeCount = joinersDates .Where(x => x < UserJoinDate).Count();
FriendsJoinedAfterCount = joinersDates .Where(x => x >= UserJoinDate).Count();

有谁知道如何计算列表中加入者日期在UserJoinDate之前有多少个日期,以及有多少个相同或之后?

编辑

以下是从即时窗口复制:

churnersDates.Count( x => x > UserChurnDate)
Expression cannot contain lambda expressions

UserJoinDate 是 DateTime

例:

UserJoinDate = 9.11.2010 0:30:00

(该值复制自日期:{9.11.2010 0:00:00} 白天: 9 星期几:星期二 年日: 313...

joinersDates.First() = 17.5.2011 0:30:00

谢谢!

如何将日期时间变量与 lambda 表达式进行比较

尝试像这样分别比较日期时间的年、月和日属性;

FriendsJoinedBeforeCount = joinersDates .Where(x => (x.Year < UserJoinDate.Year) && (x.Month< UserJoinDate.Month) && (x.Day < UserJoinDate.Day)).Count(); 

你的问题似乎是Visual Studio的限制,而不是代码中的错误。Visual Studio 2010 不支持在其"即时"或"监视"窗口中定义 lambda 表达式。

如果确实要在调试时测试 LINQ 表达式,则应将其封装到方法中,然后从"即时"窗口调用该方法。

例如:

private int GetFriendsJoinedBeforeCount(DateTime joinDate)
{
    List<DateTime> joinersDates = getJoinersDates();
    return joinersDates.Count(x => x < UserJoinDate);
}

然后,在"即时"窗口中,您将调用:

GetFriendsJoinedBeforeCount(UserChurnDate)

尝试以下代码:

List<DateTime> joinersDates = getJoinersDates();
FriendsJoinedBeforeCount = joinersDates.Count(x => x.ToUniversalTime() < UserJoinDate.ToUniversalTime());
FriendsJoinedAfterCount = joinersDates.Count - FriendsJoinedBeforeCount ;

或者尝试使用 Ticks 属性:

List<DateTime> joinersDates = getJoinersDates();
FriendsJoinedBeforeCount = joinersDates.Count(x => x.ToUniversalTime().Ticks < UserJoinDate.ToUniversalTime().Ticks);
FriendsJoinedAfterCount = joinersDates.Count - FriendsJoinedBeforeCount ;