Grouping results by month according to the datetime object in C#

I am working on an ASP.NET MVC application that includes a line chart displaying record counts and months on the X-axis and Y-axis respectively.

To achieve this, I need to make an ajax call to the controller where the model holds information such as the record creation date and the value.

However, I am struggling with grouping the data by month to display it in the format like "April has 15 records" and "May has 12 records," and so on.

Below is the structure of my model:

 public class CustomerFeedBack {
   [Key]
   public int Id {
     get;
     set;
   }
   public DateTime CreatedDate {
     get;
     set;
   } = DateTime.Now;
   public int TotalSatisfaction {
     get;
     set;
   }
 }

The javascript code for the chart currently contains dummy data. I aim to return the actual record counts for labels representing months:

var bouData = {
    // Generate the days labels on the X axis.
    labels: Array.from(new Array(30), function (_, i) {
      return i === 0 ? 1 : i;
    }),
    datasets: [{
          label: 'Satisfied',
          fill: 'start',
          data: [1500, 800, 320, 180, 240, 320, 230, 650, 590, 1200, 750, 940, 1420, 1200, 960, 1450, 1820, 2800, 2102, 1920, 3920, 3202, 3140, 2800, 3200, 3200, 3400, 2910, 3100, 4250],
          backgroundColor: 'rgba(0,123,255,0.1)',
          borderColor: 'rgba(0,123,255,1)',
          pointBackgroundColor: '#ffffff',
          pointHoverBackgroundColor: 'rgb(0,123,255)',
          borderWidth: 1.5,
          pointRadius: 0,
          pointHoverRadius: 3
        },

In the controller, I intend to return JsonResult binding the labels (month) and data (count). Below is the snippet from my incomplete controller code:

var satisfied = (from a in db.tbl_Main where a.TotalSatisfaction >= 12 
                 select new {
                  // Here I want to group by create date based on Month and sum up the values.
                 }).ToList();

I'm still learning and welcome any suggestions on how to complete this task efficiently or if there are easier alternatives.

Thank you for your help.

Update on May 19, 2022:

I have implemented the code within the JsonResult:

var satisfied = db.tbl_Main.Where(m => m.TotalSatisfaction >= 12).GroupBy(
                            m => new { m.CreatedDate.Year, m.CreatedDate.Month },
                            m => m.TotalSatisfaction
                            ).ToList();

The result shows that there are 4 records for the Month 05.

After printing the results in the console, I am now looking to display these month-wise counts on the line chart. Would returning the data in the format Month count be suitable for this purpose?

Beneath is the script where I plan to include the returned values in the chart labels for months and counts:

var bouData = {
            // Generate the days labels on the X axis.
            labels: Array.from(new Array(30), function (_, i) {
                return i === 0 ? 1 : i;
            }),
            datasets: [{
                label: 'Satisfied',
                fill: 'start',
                data: [1500, 800, 320, 180, 240, 320, 230, 650, 590, 1200, 750, 940, 1420, 1200, 960, 1450, 1820, 2800, 2102, 1920, 3920, 3202, 3140, 2800, 3200, 3200, 3400, 2910, 3100, 4250],
                backgroundColor: 'rgba(0,123,255,0.1)',
                borderColor: 'rgba(0,123,255,1)',
                pointBackgroundColor: '#ffffff',
                pointHoverBackgroundColor: 'rgb(0,123,255)',
                borderWidth: 1.5,
                pointRadius: 0,
                pointHoverRadius: 3
            },

Answer №1

Here's a snippet that can easily be translated to SQL using the ORM in your application:

var happyCustomers = db.tbl_Main
    .Where(m => m.TotalSatisfaction >= 12)
    .GroupBy(
      m => new { m.CreatedDate.Year, m.CreatedDate.Month },
      m => m.TotalSatisfaction
    )
    .Select(g => new {
       label = new DateTime(g.Key.Year, g.Key.Month, 1),
       data = g.Sum()
    })
    .ToList();

If this translation doesn't work for you, please let us know.

We are grouping the data by year and month keys, extracting only the TotalSatisfaction values from each group. Then we calculate the total satisfaction per year-month pair, providing a list of unique year-month combinations along with their corresponding satisfaction total.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Using Mongoose schema with a reference to an undefined 'ObjectID' data type

I am currently working on establishing relationships between my schemas, and I have encountered some issues with my solution. Here is how my device schema looks like: var deviceSchema = schema({ name : String, type : String, room: {type: mongo ...

Despite encountering Error 404 with AJAX XHR, the request is successfully reaching the Spring Controller

I am attempting to upload a file with a progress bar feature. var fileInput = document.getElementById('jquery-ajax-single') var form = new FormData(); form.append('uploadFile',fileInput.files[0]); $.ajax({ url: "fi ...

What is the best way to include a string in formData when making an ajax request

Is there a way to include the id when sending formdata? I need help modifying my code for better understanding. $(document).ready(function() { $("#profile_photo_form").on('submit', (function(e) { e.preventDefault(); var id = $("#update ...

The issue with collapsible elements not functioning properly in an Angular application involving CSS and JS

My implementation of collapsible in a plain HTML page looks like this: <!DOCTYPE html> <html> <head> <title></title> <style> button.accordion { background-color: #777; color: white; cursor: pointer; p ...

Prevent vertical scrolling on touch devices when using the Owl Carousel plugin

Is there a way to prevent vertical scrolling on Owl Carousel when dragging it horizontally on touch devices? It currently allows for up and down movement, causing the whole page to jiggle. If anyone has a solution, I can share the JavaScript file. Appreci ...

Error with font import causing hydration issue in NextJS

Font integration dilemma: import { Lexend } from 'next/font/google'; const lexend = Lexend({ subsets: ["latin"] }); Incorporating the font: const SplashPage = () => { ... return ( <html lang="en" className={lexend.cla ...

Dynamically scrolling using SuperScrollorama and Greensocks

I'm currently facing a JavaScript animated scroll challenge that has me scratching my head. My approach involves using the SuperScrollorama jQuery plugin, which relies on the Greensock JS tweening library. The main effect I'm aiming for is to " ...

Altering the hue of a picture

Looking to alter the color of an image on a webpage, specifically a carport. It's crucial that the texture and shadows remain consistent. Swapping out images with different colors would require an excessive amount of images, so I'm seeking advice ...

The while loop is unyielding, persisting beyond the realm of

After executing this script, it displays the HP values for both Pokemon. Pressing 1 and pressing enter subtracts your attack points from the enemy's hit points. The goal is to stop the battle when either you or the enemy reaches 0 or below hit points ...

How can I display the value entered in a text input field when using ajax upload?

Is there a way to display the value of an input type text when using ajax for file upload? I have successfully implemented code to upload files to a directory called attachments_files, but I am facing an issue. How can I retrieve and echo the value from i ...

Is it secure to use console.time() in a Node.js environment?

Looking at a small snippet of node.js code, here's what I have: console.time("queryTime"); doAsyncIOBoundThing(function(err, results) { console.timeEnd("queryTime"); // Process the results... }); Running this on my development system gives m ...

When the state of the grandparent component is updated, the React list element vanishes in the grandchild component. Caution: It is important for each child in a list to have a unique

In my development project, I've crafted a functional component that is part of the sidebar. This component consists of 3 unique elements. ProductFilters - serves as the primary list component, fetching potential data filters from the server and offer ...

Exploring TypeScript's type discrimination with objects

When working with TypeScript, type discrimination is a powerful concept: https://www.typescriptlang.org/play#example/discriminate-types But is it possible to achieve something like this? type A = {id: "a", value: boolean}; type B = {id: "b ...

Align elements on the left side with some space between them

Having trouble displaying a list of images inline within a div. When I float them left, they leave a lot of space and do not display properly. Can anyone help me with this issue? See screenshot below: Here is my html code: <div class="col75"> & ...

Testing infinite scrolling with the help of protractor

It seems like the infinite scrolling feature in ng-grid is not exactly infinite, but it's the closest comparison I could come up with for what I am observing. In our application, we are using ng-grid to display data in a table with approximately 170 ...

The AJAX request to the URL is failing

Creating a webpage with the ability to control an IP camera's movements such as moving up and down or zooming in and out involves calling specific URLs. While trying to implement this feature asynchronously, I encountered issues using AJAX which did n ...

Issues encountered with Nextjs 13.4 and Next-Auth 4.2 regarding the signIn("credentials", { }); functionality not functioning as expected

When using next-auth credentials in my current project, I encountered an issue with the signIn() function from next-auth/react. It appears that the redirection to the admin page persists regardless of whether the login details are correct or not. {error: n ...

Error Alert: LocalStorage is undefined in this context - NextJS

Having trouble retrieving access and refresh tokens from local storage. Each attempt results in a 500: Internal Server Error, with an error indicating LocalStorage is undefined. Research suggests that LocalStorage may not be compatible with rendering with ...

Obtain the complete file path using JavaScript

Imagine you have a web application utilizing NodeJS and ReactJS, both working on your local machine. In this setup, NodeJS is capable of accepting files selected from the ReactJS GUI via a simple file upload feature, like so: <input type="file" id="fil ...

Creating a local storage file named .notification.localstore.json specific to Microsoft ConversationBot

I am in need of utilizing a ConversationBot to send messages to MS Teams users. The code snippet below was obtained from an example app generated by TeamsToolkit. It functions as expected, however, it relies on user IDs stored in .notification.localstore.j ...