title: GroupBy, Sum and Count using linq
body: <p>I am trying to get a throughput view where I am calculating some stats from one table in MVC 5 using linq queries. I need to group the rows by date and count and sum of some columns</p>
  
  <p>//model</p>
  
  <pre><code>public class Assignment
  {
      public int UserId { get; set; }
      public Datetime Modified {get; set; } 
      public double TimeSpent { get; set; }}
      public string date
      {
          get
          {
              return Modified.Date.ToString("d");
          }
      }
  }
  </code></pre>
  
  <p>//controller </p>
  
  <pre><code>public ActionResult Throughputs()
  {
      var records = db.Assignments.AsEnumerable(); 
      var groups = from r in records
                   group r by r.date
                   into row
                   select new ThroughputsViewModel
                   {
                       selectedDate = row.Key,
                       Total = row.Where(x =&gt; x.TimeSpent &gt; 0).Select(x =&gt; x.UserId).Count(),
                       Total_Time = row.Sum(x =&gt; x.TimeSpent),
                       Rate = row.Where(x =&gt; x.TimeSpent &gt; 0).Select(x =&gt; x.UserId).Count() / row.Sum(x =&gt; x.TimeSpent),
                       ResAssignments = row.AsEnumerable()
                   };
      return View(records);
  }
  </code></pre>
  
  <p>//ViewModel</p>
  
  <pre><code>public class ThroughputsViewModel
  {
      public int Total { get; set; }
      public double Total_Time { get; set; }
      public double Rate { get; set; }
      public virtual User user { get; set;  }
      public int userId { get; set;  }
      public string selectedDate { get; set; }
      public IEnumerable&lt;Assignment&gt; ResAssignments { get; set; }
  }
  </code></pre>
  
  <p>When I run this either I get a nullException or the rows are not grouped by the key just the same as in the original table and the sum and count values are duplicated for each row </p>