gpt4 book ai didi

c# - 如何在 LINQ 中插入占位符以便我的组恰好有 24 个点

转载 作者:太空宇宙 更新时间:2023-11-03 19:52:37 27 4
gpt4 key购买 nike

我正在将一天的 24 小时绘制成图表,但某些时间(例如早上)没有任何意义。当那个小时没有值时,如何更改 linq 以插入“Times = 1”?

所以而不是

4、6、8、5、7、9...

应该是

1, 1, 1, 1, 4, 1, 6, 8, 5, 7, 9...(总是 24 分)

 Lead[] newLeads;

newLeads = gameManager.leads.Lead;

string[] logNumbers = (from nl in newLeads
//where DateTime.Parse(nl.CreateDate).Hour > 6
select DateTime.Parse(nl.CreateDate).Hour.ToString()
).ToArray();

var groupedLeads = logNumbers.GroupBy(x => x)
.Select(x => new { Number = x.Key, Times = x.Count() })
.ToList();

//groupedLeads.Add(new { Number = "0", Times = 1 });
//groupedLeads.Add(new { Number = "1", Times = 1 });
//groupedLeads.Add(new { Number = "2", Times = 1 });
//groupedLeads.Add(new { Number = "3", Times = 1 });
//groupedLeads.Add(new { Number = "4", Times = 1 });
//groupedLeads.Add(new { Number = "5", Times = 1 });

最佳答案

您可以使用 Enumerable.Range 获取 24 小时序列,无需 GroupBy:

var hourlyLeads = Enumerable.Range(0, 24)
.Select(h => new
{
Hour = h,
Count = newLeads.Count(nl => nl.CreateDate.Hour == h)
})
.Select(x => new
{
Number = x.Hour,
Times = x.Count == 0 ? 1 : x.Count
})
.ToList();

更新

How could I set the 'current hour' to '1' as well ? I don't want to show the current hour in progress. I could try to delete it from the collection after the linq statement but was wondering if it was easy to do in the current linq statement

不太清楚,但如果你想排除当前时间:

var hourlyLeads = Enumerable.Range(0, 24)
.Where(h => h != DateTime.Now.Hour)
.Select(h => new ........

如果您只想将当前小时设置为 1:

var hourlyLeads = Enumerable.Range(0, 24)
.Select(h => new
{
Hour = h,
Count = h == DateTime.Now.Hour ? 1 : newLeads.Count(nl => nl.CreateDate.Hour == h)
})
.Select(x => new .....

关于c# - 如何在 LINQ 中插入占位符以便我的组恰好有 24 个点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36916752/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com