LINQ:将集合中的所有时间跨度加在一起

本文关键字:时间跨度 加在一起 集合 LINQ | 更新日期: 2023-09-27 18:12:38

我试图简单地添加所有的时间跨度在我的ViewModel,但我不断得到一个错误,从这(我可以向你保证,'x.totalDuration'实际上是一个时间跨度和'myCollection'确实是一个IEnumerable:

视图:

  var myCollection = Model.Select(x => x.totalDuration);
  var ts = new TimeSpan(myCollection.Sum(r => r.Ticks)); <-- boom here--<

控制器:

 [HttpGet]
    public ActionResult List()
    {
        var model = _db.Tracks
          .Where(r => r.UserID == WebSecurity.CurrentUserId)
          .Select(x => new iOSHistoryListViewModel
          {
              averagePace = Math.Round(26.8224 / x.locations.Average(y => y.speed), 2),
              createdDate = x.createdDate,
              FirstName = x.UserProfile.FirstName,
              totalDistance = Math.Round(x.totalDistance / 1609.344, 2),
              totalDuration = TimeSpan.FromSeconds(x.totalDuration),
              trackId = x.TrackID
          })
          .OrderByDescending(x => x.createdDate)
          .ToList(); <-- tried with/without this
        return View(model);
    }
错误:

LINQ to Entities does not recognize the method 'System.TimeSpan FromSeconds(Double)' method, and this method cannot be translated into a store expression.
Description: An unhandled exception occurred during the execution of the     current web request. Please review the stack trace for more information about the error and where it originated in the code. 
Exception Details: System.NotSupportedException: LINQ to Entities does not recognize the method 'System.TimeSpan FromSeconds(Double)' method, and this method cannot be translated into a store expression.
Source Error: 

Line 13:         @{
Line 14:             var myCollection = Model.Select(x => x.totalDuration);
Line 15:             var ts = new TimeSpan(myCollection.Sum(r => r.Ticks));

这是如此简单,但我错过了一些东西…

LINQ:将集合中的所有时间跨度加在一起

问题是您正在尝试调用TimeSpan。数据库中的FromSeconds。这是一个。net方法,不能翻译。这是未经测试的,但要修复,请尝试:

        var model = _db.Tracks
      .Where(r => r.UserID == WebSecurity.CurrentUserId)
      .Select(x => new
      {
          averagePace = Math.Round(26.8224 / x.locations.Average(y => y.speed), 2),
          createdDate = x.createdDate,
          FirstName = x.UserProfile.FirstName,
          totalDistance = x.totalDistance,
          totalDuration = x.totalDuration,
          trackId = x.TrackID
      }).ToList()
      .Select(x => new iOSHistoryListViewModel{
          averagePace = x.averagePace,
          createdDate = x.createdDate,
          FirstName = x.FirstName,
          totalDistance = Math.Round(x.totalDistance / 1609.344, 2),
          totalDuration = TimeSpan.FromSeconds(x.totalDuration),
          trackId = x.trackId
      })
      .OrderByDescending(x => x.createdDate)
      .ToList();

这里的关键是第一个Select将从数据源返回的数据抛出到一个列表中。然后,列表在。net内存中,您可以在其中执行任何。net操作。然后将结果集也发送到一个新列表。这样就可以消除。fromseconds

的异常