如何将此Sql查询转换为LINQ?

时间:2011-05-04 04:45:00

标签: sql linq

我想将以下查询转换为LINQ,

  SELECT AVG(currentvalue) AS ChartAvg, 
         CONVERT(varchar(10), ReceivedDate, 103) AS RecDate
    FROM DatapointValues
   WHERE (CONVERT(varchar(10), ReceivedDate, 103) = '21/04/2011')
GROUP BY CONVERT(varchar(10), ReceivedDate, 103)

我使用下面的LINQ但不能正常工作,

from datapointvalues in db.DatapointValues
where
Convert.ToString(datapointvalues.ReceivedDate) == "21/04/2011"
group datapointvalues by new {
Column1 = Convert.ToString(datapointvalues.ReceivedDate)
} into g
select new { 
  ChartAvg = (System.Decimal?)g.Average(p => p.currentvalue),    
  g.Key.Column1    
}

1 个答案:

答案 0 :(得分:1)

查看此文章:http://msdn.microsoft.com/en-us/library/bb882657.aspx

var date = DateTime.Parse("21/04/2011");

var result = from datapointvalues in db.DatapointValues
             where datapointvalues.ReceivedDate.Date.equals(date)
             group datapointvalues by datapointvalues.ReceivedDate.Date
             into g
             select new
             { 
                 ChartAvg = g.Average(p => p.currentvalue),
                 RecDate = g.Key
             };