Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 788075
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 14, 20262026-05-14T21:18:14+00:00 2026-05-14T21:18:14+00:00

I currently have the following code to generate a sales report over the last

  • 0

I currently have the following code to generate a sales report over the last 30 days. I’d like to know if it would be possible to use linq to generate this report in one step instead of the rather basic loop I have here.

For my requirement, every day needs to return a value to me so if there are no sales for any day then a 0 is returned.

Any of the Sum linq examples out there don’t explain how it would be possible to include a where filter so I am confused on how to get the total amount per day, or a 0 if no sales, for the last days I pass through.

Thanks for your help,
Rich

    //setup date ranges to use
    DateTime startDate = DateTime.Now.AddDays(-29);
    DateTime endDate = DateTime.Now.AddDays(1);
    TimeSpan startTS = new TimeSpan(0, 0, 0);
    TimeSpan endTS = new TimeSpan(23, 59, 59);

    using (var dc = new DataContext())
    {
        //get database sales from 29 days ago at midnight to the end of today
        var salesForDay = dc.Orders.Where(b => b.OrderDateTime > Convert.ToDateTime(startDate.Date + startTS) && b.OrderDateTime <= Convert.ToDateTime(endDate.Date + endTS));

        //loop through each day and sum up the total orders, if none then set to 0
        while (startDate != endDate)
        {
            decimal totalSales = 0m;
            DateTime startDay = startDate.Date + startTS;
            DateTime endDay = startDate.Date + endTS;
            foreach (var sale in salesForDay.Where(b => b.OrderDateTime > startDay && b.OrderDateTime <= endDay))
            {
                totalSales += (decimal)sale.OrderPrice;
            }

            Response.Write("From Date: " + startDay + " - To Date: " + endDay + ". Sales: " + String.Format("{0:0.00}", totalSales) + "<br>");

            //move to next day
            startDate = startDate.AddDays(1);
        }
    }

EDIT:
Johannes answer was a great way to handle my query. Below is an adjustment to the code to get it working for this example in case anyone else has this issue. This will perform an outer join from the allDays table and return 0 values when there is no sales for that day.

var query = from d in allDays
                    join s in salesByDay on d equals s.Day into j
                    from s in j.DefaultIfEmpty()
                    select new { Day = d, totalSales = (s != null) ? s.totalSales : 0m };
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-14T21:18:14+00:00Added an answer on May 14, 2026 at 9:18 pm

    You can group all your data by day and run sum over those groups. To fulfill the requirement of having a sum for each day, even those without order, you can either join a list of all the dates or simply use a loop to make sure all dates are included. Small hint: You don’t need to set up the times explicitly if you compare by the DateTime.Date properties.

    Here’s the solution using a generator function (taken from the MoreLinq project):

    public static partial class MoreEnumerable
    {
    
        public static IEnumerable<TResult> GenerateByIndex<TResult>(Func<int, TResult> generator)
        {
            // Looping over 0...int.MaxValue inclusive is a pain. Simplest is to go exclusive,
            // then go again for int.MaxValue.
            for (int i = 0; i < int.MaxValue; i++)
            {
                yield return generator(i);
            }
            yield return generator(int.MaxValue);
        }
    
    }
    
    public class MyClass
    {
        private void test()
        {
            DateTime startDate = DateTime.Now.AddDays(-29);
            DateTime endDate = DateTime.Now.AddDays(1);
    
            using (var dc = new DataContext())
            {
                //get database sales from 29 days ago at midnight to the end of today
                var salesForPeriod = dc.Orders.Where(b => b.OrderDateTime > startDate.Date  && b.OrderDateTime <= endDate.Date);
    
                var allDays = MoreEnumerable.GenerateByIndex(i => startDate.AddDays(i)).Take(30);
    
                var salesByDay = from s in salesForPeriod
                            group s by s.OrderDateTime.Date into g
                            select new {Day = g.Key, totalSales = g.Sum(x=>(decimal)x.OrderPrice};
    
                var query = from d in allDays
                            join s in salesByDay on s.Day equals d
                            select new {Day = s.Day , totalSales = (s != null) ? s.totalSales : 0m;
    
    
                foreach (var item in query)
                {
                    Response.Write("Date: " +item.Day.ToString() " Sales: " + String.Format("{0:0.00}", item.totalSales) + "<br>");
                }
    
    
            }
        }
    }
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I currently have the following js code function clearMulti(option) { var i; var select
The following code shows what I currently have. It is an adapter for circular
I have the following code currently: <DataTemplate DataType={x:Type vm:SectionViewModel}> <ScrollViewer> <ItemsControl ItemsSource={Binding ViewModels}> </ItemsControl>
I am currently working on Problem 62 I have tried the following code to
I currently have code that does the following: private final static ExecutorService pool =
I currently have the following PHP code to control the visibility of a block:
I have the following code that currently clears all the objects in my NSManagedObjectContext:
Anything I have tried didn't work. Currenly I have following code to change asp.net
I have following code return (EseshEntities.Current.Users.Select(u => new { Comunity = u.Apartment.Building.District.City })).ToList(); if
I have the following code that creates a submenu based on current document. The

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.