0

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

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

艾伦

无法将类型为“WhereSelectEnumerableIterator 2[System.Linq.IGrouping2 [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;
4

2 回答 2

1

那是因为您的选择正在创建具有属性 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;
于 2013-02-22T13:25:05.787 回答
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;
于 2013-02-22T13:32:19.590 回答