【问题标题】:Find Date Overlapping in DataTable Using Linq C# [duplicate]使用 Linq C# 在 DataTable 中查找重叠的日期
【发布时间】:2021-02-26 07:13:27
【问题描述】:

我有一个包含 startdate 和 enddate 列的数据表。我想使用 linq 检查重叠的开始日期和结束日期。

方法输入参数:

输入数据表

startDate endDate
01/Jan/2021 31/Jan/2021
01/Feb/2021 28/Feb/2021

输入参数

开始日期:2021 年 2 月 15 日

截止日期:2021 年 2 月 20 日

预期输出:真

我创建了一个函数来检查重叠日期。

private bool IsDateOverlap(DateTime? FromDate, DateTime? ToDate, DataTable Table)
        {
            bool isOverlap = false;
            try
            {
                for (int index = 0; index < Table.Rows.Count; index++)
                {
                    if (index == this.RowID)
                        continue;
                    DateTime? rowFromDate = Convert.ToDateTime(Table.Rows[index]["startDate"]);
                    DateTime? rowToDate = Convert.ToDateTime(Table.Rows[index]["endDate"]);
                    isOverlap = (FromDate <= rowToDate && rowFromDate <= ToDate);
                    if (isOverlap)
                        break;
                }
            }
            catch (Exception ex)
            { }
            return isOverlap;
        }

它工作正常。 我想用linq来做。提前致谢。

【问题讨论】:

  • 您在寻找类似this answer 的东西吗?
  • 在您的 LINQ 语句中使用类似 row =&gt; row.Field&lt;DateTime&gt;("startDate") 的内容。这些Converts 不是必需的。
  • @Gert Arnold 没有 Linq 问题。
  • 我的意思是在您编写的 LINQ 中,通过从副本中获取代码。

标签: c# linq datatable


【解决方案1】:

我有一个方法可以帮助你如何使用自定义对象而不是数据表。

  public static List<inputDataTable> ListOfDates = new List<inputDataTable>
        {

               new inputDataTable { startDate = DateTime.Parse("01/Jan/2021"), endDate = DateTime.Parse("31/Jan/2021"),},
               new inputDataTable { startDate = DateTime.Parse("01/Feb/2021"), endDate = DateTime.Parse("28/Feb/2021"),},

        };
  

 public static bool checkOverlapping(DateTime starDate, DateTime endDate, List<inputDataTable> storeDate)
        {
            var e = storeDate.Where(a=> (starDate >= a.startDate && starDate <= a.endDate) || (endDate >= a.startDate && starDate <= a.endDate) );
            if(e.Count() > 0)
            {
                return true;
            }
            else
            {
                return false;
            }
           
        }

您也可以访问这些线程; Check dates fall within range using Linq

Check One Date is falling Between Date Range-Linq query

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-05-27
    • 2015-10-22
    • 1970-01-01
    • 2011-09-28
    • 2013-08-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多