1

I have a DataTable which has the following structure. StartDate (Type DateTime) EndDate (Type DateTime) Description (Type Text)

What I need to check is if the dates overlap or not, i.e., if the Start Date of 1 item is less than the EndDate of the previous item.

Here is the code I wrote.

NB: I already have checks to ensure that for each record, the Start Date has to be lesser than the End Date

dtDates.DefaultView.Sort = "StartDate ASC"; //Sort the DataTable based on the Start Dates
if(dtDates.Rows.Count > 1) //Check only if more than 1 Date is specified
{
    for (int i = 1; i < dtDates.Rows.Count; i++)
    {
        if(TypeConvert.ToDate(dtDates.Rows[i]["StartDate"] < TypeConvert.ToDate(dtDates.Rows[i-1]["EndDate"])
            {
                retVal = true;
                currentRow = i;
                break;
            }
     }
}

The above code works fine.

But now, I want to implement it using LINQ

So, here is the code I am trying to attempt.

How can I do the whole comparison using LINQ?

    public static bool CheckIfDatesOverlap(DataTable dataTable)
    {
        bool retVal = false;
        int currentRow = 0;
        List<DataRow> listDates = (from DataRow dgv in dataTable.Rows
                                               select dgv).OrderBy(x => x[StartDate]).ToList();
        if (listDates.Count > 1) //Perform Comparision only if more than 1 row is present
        {
            for (int i = 1; i < listDates.Count; i++)
            {
                if (TypeConvert.ToDateTime(listDates[i][StartDate]) < TypeConvert.ToDateTime(listDates[i][EndDate]))
                {
                    retVal = true; //There are duplicates, hence return true
                    currentRow = i;
                    break;
                }
                else
                {
                    //Do nothing as dates do not overlap
                }
            }
        }
        else
        {
            retVal = false; //As there is only 1 row, return false
        }
        if (retVal)
        {
            string message = "Dates Overlap";
            //Display message
        }
        return retVal;
    }
Kanini
  • 1,947
  • 6
  • 33
  • 58

1 Answers1

4

If you use SelectWithPrevious described here then you can write the following:

bool datesOverlap = table.Rows
    .Cast<DataRow>()
    .SelectWithPrevious((current, previous) => new
        {
            PreviousEndDate = (DateTime)previous["EndDate"],
            StartDate = (DateTime)current["StartDate"]
        })
    .Any(x => x.StartDate < x.PreviousEndDate);
Community
  • 1
  • 1
Paul Haley
  • 405
  • 3
  • 12
  • Jon Skeet strikes again :) Thank you for pointing it out, this helps me a lot and I'm guessing that's the answer the OP is looking for. – Vladislav Zorov Nov 16 '11 at 15:18