gpt4 book ai didi

c# - Linq to Entity 生日比较

转载 作者:太空狗 更新时间:2023-10-29 20:39:32 25 4
gpt4 key购买 nike

我需要使用 Linq to Entities 创建一个查询,其中生日必须在 2 天前和接下来的 30 天内。

以下不返回任何内容:

DateTime twoDaysAgo = DateTime.Now.AddDays(-2);
int twoDaysAgoDay = twoDaysAgo.Day;
int twoDaysAgoMonth = twoDaysAgo.Month;
DateTime MonthAway = DateTime.Now.AddDays(30);
int monthAwayDay = MonthAway.Day;
int monthAwayMonth = MonthAway.Month;
var bdays = from p in db.Staffs where EntityFunctions.TruncateTime(p.BirthDate) > EntityFunctions.TruncateTime(twoDaysAgo) &&
EntityFunctions.TruncateTime(p.BirthDate) < EntityFunctions.TruncateTime(MonthAway)
orderby p.BirthDate select p;
return bdays;

我遇到的问题是,如果生日从 11 月 3 日降到 12 月 5 日,我需要一些东西,它应该返回它。它失败的原因是生日包括年份。但是,当我使用类似的东西时:

p.BirthDate.Value.Month 

我收到了 Linq to Entities 不支持的错误。如有任何帮助,我们将不胜感激。

最佳答案

年度总结独立解决方案:

void Main()
{
var birthdays = new List<DateTime>();
birthdays.Add(new DateTime(2013, 11, 08));
birthdays.Add(new DateTime(2012, 05, 05));
birthdays.Add(new DateTime(2014, 05, 05));
birthdays.Add(new DateTime(2005, 11, 08));
birthdays.Add(new DateTime(2004, 12, 31));


foreach(var date in birthdays.Where(x => x.IsWithinRange(twoDaysAgo, MonthAway))){
Console.WriteLine(date);
}
}

public static class Extensions {
public static bool IsWithinRange(this DateTime @this, DateTime lower, DateTime upper){
if(lower.DayOfYear > upper.DayOfYear){
return (@this.DayOfYear > lower.DayOfYear || @this.DayOfYear < upper.DayOfYear);
}

return (@this.DayOfYear > lower.DayOfYear && @this.DayOfYear < upper.DayOfYear);
}
}

输出方式

DateTime twoDaysAgo = DateTime.Now.AddDays(-2);
DateTime MonthAway = DateTime.Now.AddDays(30);

8/11/2013 0:00:00
8/11/2005 0:00:00

输出方式

DateTime twoDaysAgo = new DateTime(2012, 12, 25);
DateTime MonthAway = new DateTime(2013, 01, 05);

31/12/2004 0:00:00

关于c# - Linq to Entity 生日比较,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19793775/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com