C# Linq 两个日期之间的日期

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2237440/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-07 00:39:05  来源:igfitidea点击:

C# Linq Where Date Between 2 Dates

c#linq

提问by David

I'm trying to get my linq statement to get me all records between two dates, and I'm not quite sure what I need to change to get it to work: (a.Start >= startDate && endDate)

我正在尝试使用 linq 语句来获取两个日期之间的所有记录,但我不太确定需要更改哪些内容才能使其正常工作: (a.Start >= startDate && endDate)

var appointmentNoShow =
    from a in appointments
    from p in properties
    from c in clients
    where a.Id == p.OID && (a.Start.Date >= startDate.Date && endDate)

采纳答案by Giorgi

Just change it to

只需将其更改为

var appointmentNoShow = from a in appointments
                        from p in properties
                        from c in clients
                        where a.Id == p.OID && 
                       (a.Start.Date >= startDate.Date && a.Start.Date <= endDate)

回答by Andreas Niedermair

var appointmentNoShow = from a in appointments
                        from p in properties
                        from c in clients
                        where a.Id == p.OID
                        where a.Start.Date >= startDate.Date
                        where a.Start.Date <= endDate.Date

回答by GirishBabuC

var QueryNew = _context.Appointments.Include(x => x.Employee).Include(x => x.city).Where(x => x.CreatedOn >= FromDate).Where(x => x.CreatedOn <= ToDate).Where(x => x.IsActive == true).ToList();

回答by Muhafil Saiyed

 public List<tbltask> gettaskssdata(int? c, int? userid, string a, string StartDate, string EndDate, int? ProjectID, int? statusid)
        {
            List<tbltask> tbtask = new List<tbltask>();
            DateTime sdate = (StartDate != "") ? Convert.ToDateTime(StartDate).Date : new DateTime();
            DateTime edate = (EndDate != "") ? Convert.ToDateTime(EndDate).Date : new DateTime();
            tbtask = entity.tbltasks.Include(x => x.tblproject).Include(x => x.tbUser).
                Where(x => x.tblproject.company_id == c
                    && (ProjectID == 0 || ProjectID == x.tblproject.ProjectId)
                    && (statusid == 0 || statusid == x.tblstatu.StatusId)
                    && (a == "" || (x.TaskName.Contains(a) || x.tbUser.User_name.Contains(a)))
                    && ((StartDate == "" && EndDate == "") || ((x.StartDate >= sdate && x.EndDate <= edate)))).ToList();



            return tbtask;


        }

this my query for search records based on searchdata and between start to end date

这是我基于搜索数据和开始到结束日期之间的搜索记录查询

回答by Adel Mourad

So you are scrolling down because the Answers do not work:

所以你正在向下滚动,因为答案不起作用:

This works like magic (but they say it has efficiency issues for big data, And you do not care just like me)

这就像魔术一样(但他们说它在大数据方面存在效率问题,而且你和我一样不在乎)

1- Data Type in Database is "datetime" and "nullable" in my case.

1- 在我的例子中,数据库中的数据类型是“datetime”和“nullable”。

Example data format in DB is like:

DB 中的示例数据格式如下:

2018-11-06 15:33:43.640

An in C# when converted to string is like:

转换为字符串时,C# 中的 An 类似于:

2019-01-03 4:45:16 PM

So the format is :

所以格式是:

yyyy/MM/dd hh:mm:ss tt

2- So you need to prepare your datetime variables in the proper format first:

2- 因此,您需要先以正确的格式准备日期时间变量:

Example 1

示例 1

yourDate.ToString("yyyy/MM/dd hh:mm:ss tt")

Example 2 - Datetime range for the last 30 days

示例 2 - 过去 30 天的日期时间范围

    DateTime dateStart = DateTime.Now.AddDays(-30);
    DateTime dateEnd = DateTime.Now.AddDays(1).AddTicks(-1);

3- Finally the linq query you lost your day trying to find (Requires EF 6)

3- 最后是您费力寻找的 linq 查询(需要 EF 6)

using System.Data.Entity;

_dbContext.Shipments.Where(s => (DbFunctions.TruncateTime(s.Created_at.Value) >= dateStart && DbFunctions.TruncateTime(s.Created_at.Value) <= dateEnd)).Count();

To take time comparison into account as well :

还要考虑时间比较:

(DbFunctions.CreateDateTime(s.Created_at.Value.Year, s.Created_at.Value.Month, s.Created_at.Value.Day, s.Created_at.Value.Hour, s.Created_at.Value.Minute, s.Created_at.Value.Second) >= dateStart && DbFunctions.CreateDateTime(s.Created_at.Value.Year, s.Created_at.Value.Month, s.Created_at.Value.Day, s.Created_at.Value.Hour, s.Created_at.Value.Minute, s.Created_at.Value.Second) <= dateEnd)

Note the following method mentioned on other stackoverflow questions and answers will not work correctly:

请注意,其他 stackoverflow 问题和答案中提到的以下方法将无法正常工作:

....
&&
(
    s.Created_at.Value.Day >= dateStart.Day && s.Created_at.Value.Day <= dateEnd.Day &&
    s.Created_at.Value.Month >= dateStart.Month && s.Created_at.Value.Month <= dateEnd.Month &&
    s.Created_at.Value.Year >= dateStart.Year && s.Created_at.Value.Year <= dateEnd.Year
)).count();

if the start day was in this month for example and the end day is on the next month, the query will return false and no results, for example:

例如,如果开始日在本月,结束日在下个月,则查询将返回 false 且没有结果,例如:

DatabaseCreatedAtItemThatWeWant = 2018/12/05

DatabaseCreatedAtItemThatWeWant = 2018/12/05

startDate = 2018/12/01

开始日期 = 2018/12/01

EndDate = 2019/01/04

结束日期 = 2019/01/04

the query will always search for days between 01 and 04 without taking the "month" into account, so "s.Created_at.Value.Day <= dateEnd.Day" will fail

查询将始终搜索 01 到 04 之间的天数而不考虑“月”,因此“s.Created_at.Value.Day <= dateEnd.Day”将失败

And in case you have really big data you would execute Native SQL Query rather than linq

如果您有非常大的数据,您将执行本机 SQL 查询而不是 linq

...
    ... where Shipments.Created_at BETWEEN CAST(@Created_at_from as datetime) AND CAST(@Created_at_to as datetime))
    ....

Thanks

谢谢

回答by KnuturO

I had a problem getting this to work.

我在让它工作时遇到了问题。

I had two dates in a db line and I need to add them to a list for yesterday, today and tomorrow.

我在 db 行中有两个日期,我需要将它们添加到昨天、今天和明天的列表中。

this is my solution:

这是我的解决方案:

        var yesterday = DateTime.Today.AddDays(-1);
        var today = DateTime.Today;
        var tomorrow = DateTime.Today.AddDays(1);            
        var vm = new Model()
        {
            Yesterday = _context.Table.Where(x => x.From <= yesterday && x.To >= yesterday).ToList(),
            Today = _context.Table.Where(x => x.From <= today & x.To >= today).ToList(),
            Tomorrow = _context.Table.Where(x => x.From <= tomorrow & x.To >= tomorrow).ToList()
        };

回答by Sumesh Sukumaran

If someone interested to know how to work with 2 list and between dates

如果有人有兴趣知道如何使用 2 个列表和日期之间

var newList = firstList.Where(s => secondList.Any(secL => s.Start > secL.RangeFrom && s.End < secL.RangeTo))

回答by Tomá? Opis

If you have date interval filter condition and you need to select all records which falls partly into this filter range. Assumption: records has ValidFrom and ValidTo property.

如果您有日期间隔过滤条件,并且您需要选择部分属于此过滤范围的所有记录。假设:记录具有 ValidFrom 和 ValidTo 属性。

DateTime intervalDateFrom = new DateTime(1990, 01, 01);
DateTime intervalDateTo = new DateTime(2000, 01, 01);

var itemsFiltered = allItems.Where(x=> 
    (x.ValidFrom >= intervalDateFrom && x.ValidFrom <= intervalDateTo) ||
    (x.ValidTo >= intervalDateFrom && x.ValidTo <= intervalDateTo) ||
    (intervalDateFrom >= x.ValidFrom && intervalDateFrom <= x.ValidTo) ||
    (intervalDateTo >= x.ValidFrom && intervalDateTo <= x.ValidTo)
);