c# - Create list of months reoccurrence to be used in timeline chart
问题描述
I have a list dates in C# and I want to create a list of (Month, Count).
Example:
01/01/2021
05/01/2021
10/03/2021
etc..
Expected List will be:
January,2
February,0
March,1
What is the best approach?
解决方案
您必须定义在您的情况下最好的方法是什么(最快、最易读等)。例如,您可以尝试Linq ( GroupJoin ):
using System.Globalization;
using System.Linq;
...
// Given list of dates...
List<DateTime> dates = new List<DateTime>() {
new DateTime(2021, 1, 1),
new DateTime(2021, 1, 5),
new DateTime(2021, 3, 10),
};
...
// ... we query it with a help of Ling GroupJoin
var result = Enumerable
.Range(1, 12)
.GroupJoin(dates,
index => index,
date => date.Month,
(index, src) => $"{CultureInfo.CurrentCulture.DateTimeFormat.MonthNames[index - 1]},{src.Count()}")
.ToList();
// Let's have a look
Console.WriteLine(string.Join(Environment.NewLine, result));
结果:
January,2
February,0
March,1
April,0
May,0
June,0
July,0
August,0
September,0
October,0
November,0
December,0
推荐阅读
- php - 根据 PHP 中的计数和百分比选择候选人
- python - Python:一个存储库中有多个包还是每个存储库一个包?
- java - ARcore Cloud Anchor 有一个监听器知道 Cloud Anchor 何时托管?
- c# - 用于 ping 应用程序以检查网络节点的伪代码
- python - 如何过滤熊猫中的日期列?
- keras - 使用 keras 在 cnn 中预测我自己的图像
- jquery - 滚动回窗口顶部时,scrollTop 位置不正确
- symfony - How to validate data in a custom controler
- javascript - 为什么使用 API 上传 Word OfficeJS PDF 文档会保存一个空的 PDF 文档
- java - Java 可插件化应用程序消费者如何加载接口?