Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# - How to find most frequent date from list

Tags:

c#

linq

group-by

I seem to have drawn a blank. I have a list of sales, retrieved like so:

List<Sales> sales = ctn.Sales.Where(s => s.DateSold >= request.FromDate && s.DateSold <= request.ToDate).ToList();

An item in the list of sales would look something like the following:

SaleID | DateSold | ProductID | ShopID

As part of a report, I would like to return to the user a simple string informing them of what day is the day that tends to sell the most.

So I think what I should do is group sales by day, get a count for each day, and then evaluate which has the highest number, however I'm not sure exactly how to do this.

Can anyone help?

like image 441
109221793 Avatar asked Dec 21 '25 11:12

109221793


2 Answers

You just have to group on the DateSold and then order by the count (which tells you how many items belong to the group):

salesByDay = sales.GroupBy(s => s.DateSold).OrderBy(g => g.Count());
like image 66
Justin Niessner Avatar answered Dec 23 '25 01:12

Justin Niessner


If you set the exact DateTime of sold item into DateSold, you probably want to take Date part and group by it

from sale in sales
group sale by sale.DateSold.Date into grouped
orderby grouped.Count()
select new {Date = grouped.Key, Count = grouped.Count()};
like image 24
Ilya Ivanov Avatar answered Dec 23 '25 01:12

Ilya Ivanov