查找最小日期时间并将日期时间分配给本地变量

时间:2013-02-22 13:21:38

标签: c# asp.net-mvc linq

我正在尝试获取最小日期时间,然后是最大日期时间并比较两者。但是,当我尝试从LINQ中提取DateTime值时,我收到以下错误。任何帮助将不胜感激。

此行引发错误:appChartDateStart = Convert.ToDateTime(dateStartType);

阿伦

  

无法转换'WhereSelectEnumerableIterator 2[System.Linq.IGrouping 2 [System.DateTime,LatencyApp.Domain.Models.ChartHist],<> f__AnonymousType2`1 [System.DateTime]]'类型的对象以输入'System'。 IConvertible”。

我的代码:

        DateTime appChartDateStart = DateTime.MinValue;
        DateTime appChartDateEnd = DateTime.MinValue;
        var dateStartType = from row in myRow
                                group row by row.LoginDateTime_Rounded into g
                                select new { MinDateTime = g.Min(row => row.LoginDateTime_Rounded) };
        var dateEndType = from row in myRow
                                group row by row.LoginDateTime_Rounded into g
                                select new { MinDateTime = g.Max(row => row.LoginDateTime_Rounded) };
        appChartDateStart = Convert.ToDateTime(dateStartType);
        appChartDateEnd = Convert.ToDateTime(dateEndType);
        TimeSpan difAppChart = appChartDateEnd - appChartDateStart;

2 个答案:

答案 0 :(得分:1)

那是因为你的select正在创建一个带有属性MinDateTime的匿名类型。 Convert.TomDateTime方法不知道如何转换此匿名类型。尝试做:

DateTime appChartDateStart = DateTime.MinValue;
DateTime appChartDateEnd = DateTime.MinValue;
var dateStartType = (from row in myRow
                        group row by row.LoginDateTime_Rounded into g
                        select new { MinDateTime = g.Min(row => row.LoginDateTime_Rounded) }).FirstOrDefault();
var dateEndType = (from row in myRow
                        group row by row.LoginDateTime_Rounded into g
                        select new { MinDateTime = g.Max(row => row.LoginDateTime_Rounded) }).FirstOrDefault();
appChartDateStart = Convert.ToDateTime(dateStartType);
appChartDateEnd = Convert.ToDateTime(dateEndType);
TimeSpan difAppChart = appChartDateEnd - appChartDateStart;

答案 1 :(得分:1)

我在LINQ sintax中做过,它工作得很好,也有点干净了:

DateTime appChartDateStart = DateTime.MinValue;
DateTime appChartDateEnd = DateTime.MinValue;

var dateStartType = myRow.GroupBy(x => x.LoginDateTime_Rounded).Select(x => x.Key).Min();
var dateEndType = myRow.GroupBy(x => x.LoginDateTime_Rounded).Select(x => x.Key).Max();

TimeSpan difAppChart = appChartDateEnd - appChartDateStart;

完成代码:

        DateTime appChartDateStart = DateTime.MinValue;
        DateTime appChartDateEnd = DateTime.MinValue;
        if (histByApp.Count() != 0)
        {
            var dateStartType = histByApp.GroupBy(x => x.LoginDateTime_Rounded).Select(x => x.Key).Min();
            var dateEndType = histByApp.GroupBy(x => x.LoginDateTime_Rounded).Select(x => x.Key).Max();
            appChartDateStart = Convert.ToDateTime(dateStartType);
            appChartDateEnd = Convert.ToDateTime(dateEndType);
        }
        TimeSpan difAppChart = appChartDateEnd - appChartDateStart;