gpt4 book ai didi

c# - 日期之间的 Linq 复杂查询搜索

转载 作者:行者123 更新时间:2023-11-29 09:28:57 25 4
gpt4 key购买 nike

我有这个模型,保存列表月份 1 月 - 12 月。我希望用户设置日志的开始日期,例如 12 月 26 日到 1 月 25 日或 1 月 1 日到 1 月 31 日

 public class SalaryMonth
{
public int Id { get; set; }

public int StartMonth { get; set; }
public int StartDay { get; set; }

public int EndMonth { get; set; }
public int EndDay { get; set; }

public string Name { get; set; }

}

如何根据提供的日期获取 SalaryMonth,但这是我的业务逻辑,但总是返回 null 一个月

namespace Contracts.Attendances
{


public interface IAttendanceService
{
Task<SalaryMonth> GetASalaryMonthByDate(DateTime date);

}

public class AttendanceService : IAttendanceService
{

/.../

public async Task<SalaryMonth> GetASalaryMonthByDate(DateTime date) {
var day = date.Day;
var month = date.Month;
var result = await _context.SalaryMonths.
.FirstOrDefaultAsync(p => (p.StartMonth == month && p.StartDay >= day && p.StartDay <= day)
|| ( p.EndMonth == month && p.EndDay >= day && p.EndDay <= day));

return result;
}

}
}

来自数据库的 Json

{
"SalaryMonth": [
{
"Id": "3",
"StartMonth": "2",
"StartDay": "26",
"EndMonth": "3",
"EndDay": "25",
"Name": "March"
},
{
"Id": "4",
"StartMonth": "3",
"StartDay": "26",
"EndMonth": "4",
"EndDay": "25",
"Name": "April"
},
{
"Id": "5",
"StartMonth": "4",
"StartDay": "26",
"EndMonth": "5",
"EndDay": "25",
"Name": "May"
},
{
"Id": "6",
"StartMonth": "5",
"StartDay": "26",
"EndMonth": "6",
"EndDay": "25",
"Name": "June"
},
{
"Id": "7",
"StartMonth": "6",
"StartDay": "26",
"EndMonth": "7",
"EndDay": "25",
"Name": "July"
},
{
"Id": "8",
"StartMonth": "7",
"StartDay": "26",
"EndMonth": "8",
"EndDay": "25",
"Name": "August"
},
{
"Id": "9",
"StartMonth": "8",
"StartDay": "26",
"EndMonth": "9",
"EndDay": "25",
"Name": "September"
},
{
"Id": "10",
"StartMonth": "9",
"StartDay": "26",
"EndMonth": "10",
"EndDay": "25",
"Name": "October"
},
{
"Id": "11",
"StartMonth": "10",
"StartDay": "26",
"EndMonth": "11",
"EndDay": "25",
"Name": "November"
},
{
"Id": "12",
"StartMonth": "11",
"StartDay": "26",
"EndMonth": "12",
"EndDay": "25",
"Name": "December"
},
{
"Id": "2",
"StartMonth": "2",
"StartDay": "26",
"EndMonth": "2",
"EndDay": "25",
"Name": "February"
},
{
"Id": "1",
"StartMonth": "12",
"StartDay": "26",
"EndMonth": "1",
"EndDay": "25",
"Name": "January"
}
]
}

如何查询记录以允许用户从提供的日期获取工资月份。示例用户提供 2019 年 12 月 26 日至 2020 年 1 月 26 日之间的任何日期,结果必须是一月,因为该日期位于一月中,因为一月 StartMonth 为 12,StartDate 26,EndMonth 为 1,EndDate 25

最佳答案

所以我想我知道你想做什么。如果我理解正确的话,那么你的 linq 调用中的逻辑有点困惑。给定任何一天,该天不能小于或等于某个日期,也不能大于或等于该同一日期,除非它是同一日期。

所以你需要这样做:

C# 代码:

.FirstOrDefaultAsync(p => (p.StartMonth == month && p.StartDay <= day) || ( p.EndMonth == month && p.EndDay >= day ));

希望这有帮助。

关于c# - 日期之间的 Linq 复杂查询搜索,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59114384/

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