关于c#:如何使用linq按月查询计数和分组

How to write a count and group by month query with linq

这是我在ASP.NET核心中使用Entity Framework核心的第一个C应用程序,我正在尝试在Linq中编写以下MySQL查询:

1
2
3
SELECT districtid, COUNT(id), MONTH(registerDate)
FROM StreetCrimes
GROUP BY districtid, MONTH(registerDate)

我面临的问题是编写LINQ代码。为了接近答案,我尝试了以下方法:

1
2
3
4
5
var StreetCrimes = this.database.StreetCrimes
        .Select(s => s.district)
        .Count(s => s.id > 0)
        .GroupBy(s => s.district)
        .ThenBy(s => s.registerDate);

如果能帮上忙,我们将不胜感激。

我的StreetCrime班:

1
2
3
4
5
6
7
8
9
public class StreetCrime
{
    public int id { get; set; }

    public string caseNumber { get; set; }
    public District district { get; set; }
    public DateTime registerDate { get; set; }
    public TimeSpan crimeTime { get; set; }
}


地区需要继承IEqualityComparer,GroupBy才能工作。LINQ应该如下所示:

1
2
3
4
5
       var StreetCrimes = this.database.StreetCrimes
       .Where(x => x.id > 0)
       .GroupBy(s => new {district = s.district, date = s.registerDate})
       .Select(x => new { count = x.Count(), district = x.Key.district, date = x.Key.date})
       .ToList();

这应该有效:

1
2
3
4
5
var StreetCrimes = this.database.StreetCrimes
       .Where(x => x.id > 0)
       .GroupBy(s => new {district = s.district, month = s.registerDate.Month})
       .Select(x => new { count = x.Count(), district = x.Key.district, month = x.Key.month})
       .ToList();


多亏了@jdweng,我才更接近答案。不过,我每个月都需要这笔钱。

1
2
3
4
5
        var StreetCrimes = this.database.StreetCrimes
        .Where(x => x.id > 0)
        .GroupBy(s => new {district = s.district, date = s.registerDate.Month})
        .Select(x => new { count = x.Count(), district = x.Key.district, date = x.Key.date})
        .ToList();

你可以和林肯一起去

1
2
3
4
5
  var StreetCrimes = this.database.StreetCrimes
   .Where(x => x.id > 0)
   .GroupBy(s => new {district = s.district, date = s.registerDate})
   .Select(x => new { count = x.Count(), district = x.Key.district, date = x.Key.date})
   .ToList();

但是你也可以用一个DataTable

1
2
3
4
5
6
SqlCommand cmd = new SqlCommand("SELECT districtid,COUNT(id),MONTH(registerDate) FROM StreetCrimes GROUP BY districtid,MONTH(registerDate)",connectionString)

DataTable dt = new DataTable();
SqlDataAdapter ada = new SqlDataAdapter(cmd);
ada.Fill(dt)
int crimeCount = dt.Rows.Count();

或者两行行可以:

1
2
3
 SqlCommand cmd = new SqlCommand("SELECT districtid,     COUNT(id),MONTH(registerDate) FROM StreetCrimes GROUP BY districtid,MONTH(registerDate)",connectionString)

 int crimeCount = CInt(cmd.ExecuteScalar());