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

Update the button text dynamically when clicked without using an identifier or a class

If we take a look at my button in the following code: <input type="button" value="BLUE" name="button_blue" /> My goal is to have the value="BLUE" changed to value="RED" or any other desired value when the button is clicked. ...

The image file that was uploaded from a React Native iOS application to Azure Blob Storage appears to be corrupted or incomplete as it is not

Struggling to develop a feature in a React Native mobile app where users can upload and crop their profile picture, then store it in Azure blob storage. I encountered difficulty with implementing react-native-fs as many resources recommended it, but I kep ...

Differentiating the angular distinction between setting a variable with ng-click and invoking a function

I've encountered a situation like this before. Let's assume the controller has these variables: $scope.valueArr = ['Hello', 'No', 'Yes']; $scope.myValue = 'Hello'; And there is an ng-repeat as follows: ...

Disregard any labels when it comes to clickable areas for mouse events

Here is a simple example in JSFiddle where a text is displayed over an image inside a div element. Depending on where the cursor hovers, it can exhibit three different behaviors: pointing hand over the image, allowing text selection over the content of the ...

How can Vue be used to dynamically change the input type on focus?

What Vue method do you recommend for changing an input element's type on focus? e.g. onfocus="this.type = 'date'" I am specifically looking to switch the input type from text to date in order to utilize the placeholder property. ...

Implementing a nested ng-repeat for organizing limited data

I'm working with a nested ng-repeat setup like this: <div ng-repeat="item_l in list1"> <div ng-repeat="item_f in list2"> {{item_f}} {{item_l}} </div> </div> Currently, this code is producing around 20 results. ...

How can a tab be created using a link within a tab using jquery easyui?

Tabs documentation My goal is to add a new tab from a link within an existing tab. For instance, in tab A, there should be a link "open tab B" that when clicked, adds tab B. I have attempted to create a tab with a link outside of the tab (which works). ...

Tips for expanding a fabric canvas to match the entire width of its parent division

specific scenario I have a cloth canvas placed inside a main section. How can I expand the canvas to cover the entire width and height of its container? Here is what my current code looks like: <div class="design_editor_div"> &l ...

I am unable to generate a vite application within WSL

My system is running node version 10.19.0 and npm version 6.14.4. Whenever I try to run create-vite@latest client, I encounter the following error: npx: installed 1 in 0.79s /home/victor/.npm/_npx/86414/lib/node_modules/create-vite/index.js:3 import &apos ...

The function is trying to access a property that has not been defined, resulting in

Here is a sample code that illustrates the concept I'm working on. Click here to run this code. An error occurred: "Cannot read property 'myValue' of undefined" class Foo { myValue = 'test123'; boo: Boo; constructor(b ...

Attempting to implement a disappearing effect upon submission with the use of JavaScript

I am currently working on implementing a disappearing form feature for a small web application. The idea is that once the initial form is submitted, it will be replaced by a new form. While my current code somewhat works, it only lasts for a brief moment b ...

Showing changes in state in real-time using ReactJS: A quick guide

Hello, I am currently facing an issue while trying to add a comment and display it immediately on the DOM. Whenever I type any word in the form box, it does not appear in the box. Additionally, pressing the enter key does not trigger a POST request. Could ...

Npm is unable to locate the package.json file in the incorrect directory

Hello, I am currently in the process of setting up webpack. I have all the configurations ready, but when I attempt to execute webpack in my terminal, it looks for the package.json file in the incorrect location. Is there a way for me to modify the path ...

Rails 3.2 - form mistakenly submitted repeatedly

I am working on a project involving the Box model, which includes many box_videos. I have created an edit form to allow users to add box_videos to the box after it has been created: <%= form_tag "/box_videos", { method: :post, id: "new_box_videos", rem ...

How can I make sure certain properties in the Vuex store don't retain their state after a redirect during server-side rendering (SSR)?

Our approach involves server-side rendering with the use of preserveState to persist all vuex modules' state when navigating between pages. However, we have a specific store where we need to exclude certain properties from persistence. Is there a sol ...

The Vue ChartJS fails to display properly after the page is refreshed

Although this issue may appear to be a common one, some of the suggested solutions are outdated or no longer functional. My objective is to ensure that the chart remains responsive even after the page reloads. I attempted to implement the solution provided ...

Running Selenium tests on multiple machines can be achieved by using the Run Functional Test build step within the TFS build setup

I currently have almost 7000 test cases written using the MSTest Framework. These test cases have been categorized into groups A, B, C, D, E, F, and G, each containing 1000 test cases. With a total of 7 virtual machines (VMs) at my disposal, I am aiming t ...

Tips for displaying a populated ViewBag string from a try/catch block on the screen

I'm currently working on parsing a JSON file in my controller and implementing try/catch functionality for any errors that may arise. When an error occurs during the JSON parsing process, I populate ViewBag with the error message and attempt to displa ...

What advantages can be found in using various CRUD techniques?

When working with CRUD operations, the process can be done using a form like this: <form action="/todo/<%= todos[i]._id %>?_method=DELETE" method="POST> <button>x</button> </form> The corresponding con ...

Submit a form to the same page without reloading and toggle the visibility of a div after submission

Is there a way to submit a form without refreshing the page and hiding the current div while showing a hidden one? I attempted to use the following code, but it ends up submitting the form and reloading the page. <form method="post" name="searchfrm" a ...