LINQ:add/sum 集合中的所有时间跨度在一起

LINQ: add/sum all timespans in a collection together

我试图简单地将我的 ViewModel 中的所有 TimeSpans 相加,但我一直收到错误(我可以向你保证 'x.totalDuration' 实际上是一个 TimeSpan 而 '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));

这很简单,但我遗漏了一些东西...

问题是您正试图在数据库中调用 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

的异常