在C#搜索linq的日期 [英] Search dates in linq in C#
问题描述
我有员工工资修改历史
并且需要查找搜索期间的工资是什么
薪水在以下日期被修改
08/03/2017它是2200美元,变成2300
24 / 12/2018它是2300 US并且变成了2400
25/12/2018它是2400美元并且变成2300
17/02/2019它是2300美国并且变成了2400
如果我在 26/01/2017至2017年2月25日期间搜索工资如果我在 26/02/2017至2017年3月25日期间搜索工资,我预计结果为2200
如果我在 26/11/2018至2017年12月25日期间搜索工资,我预计结果为2300
如果我在 26/12/2018至25/01/2019期间搜索工资,我预计结果为2400
你希望结果是2300
我的c#代码的问题是它从2017年3月8日到2017年2月17日返回整个日期
在上述搜索时段的任何时段
i需要上述预期结果我能做些什么来获得正确的结果
我尝试过:
i have employee salary modification history
and need to find what is the salary for the searched period for example
salary have been modified in the following dates
08/03/2017 it was 2200 US and became 2300
24/12/2018 it was 2300 US and became 2400
25/12/2018 it was 2400 US and became 2300
17/02/2019 it was 2300 US and became 2400
if i searched for salary at the period from 26/01/2017 to 25/02/2017 i expect the result to be 2200
if i searched for salary at the period from 26/02/2017 to 25/03/2017 i expect the result to be 2300
if i searched for salary at the period from 26/11/2018 to 25/12/2017 i expect the result to be 2400
if i searched for salary at the period from 26/12/2018 to 25/01/2019 i expect the result to be 2300
the problem with my c# code that it return the whole dates from 08/03/2017 to 17/02/2019
at any period from the searched periods above
i need the above expected results what can i do to obtain correct result
What I have tried:
var dbitem = db.tblSalaryHistories.Where(c => c.Employee_ID == employeeId && (
(startDate <= c.Update_Date && endDate >= c.Update_Date) ||
(startDate >= c.Update_Date && endDate <= c.Update_Date) ||
(startDate <= c.Update_Date) ))
推荐答案
问题是你的代码完全符合你的要求:返回所有数据。
这是因为你有OR条件相当于:
The problem is that your code does exactly what you ask of it: returns all data.
This is because you have OR conditions which amount to:
(a <= b && c >= b) || (a >= b && c <= b) || (a <= b)
因此,如果在任何时候,a< b,整个条件都是真的。第一个条件是无关紧要的,因为第三个条件在第一个条件时始终为真。
因此,如果您搜索26-01-2017的startDate,if会自动匹配样本数据中的所有行,并返回它们。
如果您提供订单 - 也许是通过c.UpdateDate升序,您可以使用FirstOrDefault而不是Where返回单行,但即便如此,我认为您希望看得更接近在您的情况下,可能会将其减少到
So, if at any time, a < b, the whole condition is true. The first condition is irrelevant because the third will always be true when the first is.
So if you search for a startDate of 26-01-2017, if will automatically match all rows in your sample data, and return them.
If you provide an order - perhaps by c.UpdateDate ascending, you could use FirstOrDefault instead of Where to return a single row, but even then, I think you want to look rather more closely at your condition and probably reduce it to
startDate <= c.Update_Date && endDate >= c.Update_Date
这篇关于在C#搜索linq的日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!