2015-05-19 52 views
0

我有四列数据表:Date,isin,PriceState
我需要从Date列中获取最小和最大日期。
我正在使用这段代码,它可以很好地处理一个文件,但是与其他文件显示我错误的最大日期。最小和最大数据表数据表

DateTime stDate = Convert.ToDateTime((excleTable.Compute("min(date)", string.Empty))); 
DateTime eDate = Convert.ToDateTime((excleTable.Compute("max(date)", string.Empty))); 

例如在第一行,我有02/27/2015和最后一排,我有03/31/2015但它只能读取,直到03/09/2015这是不正确。
任何想法我该怎么办?

+0

什么是你列的'DataType'?看起来像是'字符串'而不是'DateTime' – Habib

+0

是它的字符串数据类型 – Dev

回答

1

看起来你的列类型不是DateTime。如果你能解决这个问题比确保您DataTableDateTime类型date列,否则,你可以使用LINQ的MaxMin和你列转换为DateTime,如:

DateTime stDate = dt.AsEnumerable() 
        .Max(r => Convert.ToDateTime(r.Field<string>("date"))); 

DateTime eDate = dt.AsEnumerable() 
        .Min(r => Convert.ToDateTime(r.Field<string>("date"))); 

您可能需要使用DateTime.ParseExact转换到DateTime,如果你的字符串值不符合缺省的/可DateTime格式,如:

DateTime stDate = dt.AsEnumerable() 
    .Max(r => DateTime.ParseExact(r.Field<string>("date"), 
            "MM/dd/yyyy", 
            CultureInfo.InvariantCulture)); 
+0

在我的情况下工作我想知道为什么我的两行代码不能用任何方式处理一个文件谢谢 – Dev

+0

@Tahir,字符串类型,它会使用自然排序顺序,而不是您期望的“DateTime”排序顺序。 – Habib