简体   繁体   English

C# - 如何从列表中找到最常见的日期

[英]C# - How to find most frequent date from list

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 | SaleID | DateSold | DateSold | ProductID | ProductID | ShopID 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? 有人可以帮忙吗?

您只需要在DateSold上进行DateSold ,然后按计数排序(它告诉您有多少项属于该组):

salesByDay = sales.GroupBy(s => s.DateSold).OrderBy(g => g.Count());

If you set the exact DateTime of sold item into DateSold, you probably want to take Date part and group by it 如果您将已售商品的确切日期时间设置为DateSold,您可能希望按日期部分和分组

from sale in sales
group sale by sale.DateSold.Date into grouped
orderby grouped.Count()
select new {Date = grouped.Key, Count = grouped.Count()};

这将为您提供销售最多的日期:

sales.GroupBy(x => x.DateSold).OrderByDescending(g => g.Count()).FirstOrDefault().Key;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM