【问题标题】:Sorting a DataTable using LINQ使用 LINQ 对数据表进行排序
【发布时间】:2011-11-16 12:08:39
【问题描述】:

我有一个具有以下结构的 DataTable。 开始日期(类型日期时间) 结束日期(类型日期时间) 描述(类型文本)

我需要检查的是日期是否重叠,即 1 项的开始日期是否小于前一项的结束日期。

这是我写的代码。

注意:我已经检查以确保对于每条记录,开始日期必须小于结束日期

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;
            }
     }
}

上面的代码工作正常。

但现在,我想使用 LINQ 来实现它

所以,这是我尝试尝试的代码。

如何使用 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;
    }

【问题讨论】:

    标签: linq c#-3.0


    【解决方案1】:

    如果你使用 SelectWithPrevious 描述的here 那么你可以写如下:

    bool datesOverlap = table.Rows
        .Cast<DataRow>()
        .SelectWithPrevious((current, previous) => new
            {
                PreviousEndDate = (DateTime)previous["EndDate"],
                StartDate = (DateTime)current["StartDate"]
            })
        .Any(x => x.StartDate < x.PreviousEndDate);
    

    【讨论】:

    • Jon Skeet 再次罢工 :) 感谢您指出这一点,这对我很有帮助,我猜这就是 OP 正在寻找的答案。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-28
    • 1970-01-01
    • 2017-05-18
    • 1970-01-01
    相关资源
    最近更新 更多