1

This is my first C# application in ASP.NET Core using Entity Framework Core and I'm trying to write the following MySQL query in Linq:

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

The problem I'm facing is writing the linq code. I've tried the following to get close to the answer:

var StreetCrimes = this.database.StreetCrimes
        .Select(s => s.district)
        .Count(s => s.id > 0)
        .GroupBy(s => s.district)
        .ThenBy(s => s.registerDate);

Any help making this possible would be appreciated.

My StreetCrime class:

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; }
}
Debreker
  • 206
  • 4
  • 12

4 Answers4

3

District needs to inherit IEqualityComparer for the GroupBy to work. The linq should look like this :

       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();
jdweng
  • 33,250
  • 2
  • 15
  • 20
3

Thanks to @jdweng I got closer to my answer. However I Needed the total amount each month.

        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();
Debreker
  • 206
  • 4
  • 12
0

You can go with LINQ

  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();

but you can also go with a DataTable.

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();

or maybe two lines will do :

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

 int crimeCount = CInt(cmd.ExecuteScalar());
Software Dev
  • 5,368
  • 5
  • 22
  • 45
0

This should work:

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();