1

我有一个dt包含两列FromDateToDate. 我有两个文本框,我在其中输入日期blackOutFromDateblackOutToDate. 说,我的 DataTable 中有 7 行dt

From Date       To Date      
8/21/2012   To  8/22/2012   
8/23/2012   To  8/24/2012   
8/25/2012   To  8/25/2012   
8/5/2012    To  8/6/2012    
8/26/2012   To  8/27/2012   
8/1/2012    To  8/2/2012    
8/3/2012    To  8/3/2012

如果我在文本框中输入的值CheckInDate介于CheckOutDateDataTable 的任何匹配日期范围之间dt,它应该返回具有此类匹配的行数的计数。

我在做

foundRows = _blackOutTable.Select
                               (
                                   "(FromDate <='" +     
blackOutFromDate.ToShortDateString() + "' AND ToDate >= '" + 
blackOutFromDate.ToShortDateString() + "')"
                                   + "OR (FromDate <='" + 
blackOutToDate.ToShortDateString() + "' AND ToDate >='" + 
blackOutToDate.ToShortDateString() + "')"
                                   + "OR (FromDate >='" + 
blackOutFromDate.ToShortDateString() + "' AND FromDate <='" +     
blackOutToDate.ToShortDateString() + "')"
                                   + "OR (ToDate >= '" +   
blackOutFromDate.ToShortDateString() + "' AND ToDate <='" +     
blackOutToDate.ToShortDateString() + "')"
                               );
if (foundRows.Length == 0)
{
}

编辑:我将在 SQl 服务器中归档的 DateFrom 和 DateTo 存储为

CAST(MONTH(date1) AS VARCHAR(2)) + '/' + CAST(DAY(date1) AS VARCHAR(2)) + '/' +     
CAST(YEAR(date1) AS VARCHAR(4))  [fromdate],
        CAST(MONTH(date2) AS VARCHAR(2)) + '/' + CAST(DAY(date2) AS 
VARCHAR(2)) + '/' + CAST(YEAR(date2) AS VARCHAR(4))  [todate]

blackOutFromDate 和 blackOutFromDate 属于 DateTime 类型。

但它没有返回正确的值。选择表达式存在一些问题。我能做些什么来解决这个问题?

4

3 回答 3

0

这是DataTable.Select语法for DateTimes

foundRows = _blackOutTable.Select("FromDate >= #2012-07-13#")

因此,您需要使用String.Format将日期变量放入该字符串中。

编辑:由于您的日期时间已转换为 varchar 并且您无法更改它,因此您需要将它们解析回日期时间。我建议使用Linq-To-DataSet

DataTable tblFiltered;
var invCulture=System.Globalization.CultureInfo.InvariantCulture;
var filteredRows = _blackOutTable.AsEnumerable()
    .Where(r => DateTime.Parse(r.Field<String>("FromDate"), invCulture) >= blackOutFromDate
             && DateTime.Parse(r.Field<String>("ToDate"),   invCulture) <= blackOutToDate);

if (filteredRows.Any())
{
    tblFiltered = filteredRows.CopyToDataTable();
}

您可以使用foreach枚举所有行或使用CopyToDataTableDataTable过滤的DataRows.

于 2012-07-18T08:23:59.867 回答
0

你为什么不在数据库上做这个?

WHERE (1=1) 
AND 
( 
    @in_ReportingDate BETWEEN Cast(Floor(Cast(ZO_RMArea_DateFrom As Float)) As DateTime) AND Cast(Floor(Cast(ZO_RMArea_DateTo As Float)) As DateTime) 
    OR ZO_RMArea_DateFrom IS NULL 
    OR ZO_RMArea_DateTo IS NULL 
) 

还要注意 - 你有 DateTime 值,如果你做 ToShortDateString,它将是 date.00:00:00.000,而 FromDate 可以是 date.23:59:59.995

这就是 Cast(Floor(Cast 的用途。在比较中截断时间。

于 2012-07-18T08:33:35.377 回答
0

试试这个

int rowCount = blackOutTable.AsEnumerable()
            .Count(c => ((DateTime)c["FromDate"]) >= blackOutFromDate && ((DateTime)c["ToDate"]) <= blackOutToDate);
于 2012-07-18T09:19:41.563 回答