linq groupby Months 并将任何缺失的月份添加到分组数据中
我创建了一个 linq 语句,它似乎工作正常。我可能写得正确,也可能不正确,但它返回了我的预期结果。
var grouped = RewardTransctions.GroupBy(t => new
{
t.PurchaseDate.Value.Month
}).Select(g => new TransactionDetail()
{
Month =
g.Where(w=>w.EntryType==1).Select(
(n =>
n.PurchaseDate.Value.Month))
.First(),
TransactionAmount = g.Count()
});
现在结果返回 5 个按月份分组的值。是否可以将 TransactionAmount = 0 的其他 7 个缺失月份添加到其中?
我疯狂的原因是我试图将这些值绑定到图表上,并让我的 x 轴基于月份。目前仅显示 5 个月的记录。如果我的数据一个月没有返回任何值,我想添加 0 值。
有什么建议吗?
I have created a linq statement which seems to be working ok. I may or maynot have written it correctly however its returning my expected results.
var grouped = RewardTransctions.GroupBy(t => new
{
t.PurchaseDate.Value.Month
}).Select(g => new TransactionDetail()
{
Month =
g.Where(w=>w.EntryType==1).Select(
(n =>
n.PurchaseDate.Value.Month))
.First(),
TransactionAmount = g.Count()
});
Now the results are returning 5 values grouped by months. Is it possible to add the 7 other missing months with a TransactionAmount = 0 to them?
The reason for my madness is I am trying to bind these values to a chart and having my x axis based on months. Currently its only showing the 5 months of records. If my data doesnt return any value for a month I some how want to add in the 0 value.
Any suggestions?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
如果使用
.ToLookup(...)
,就非常简单。对于几个简单的 LINQ 查询来说怎么样?
It's very simple if you use
.ToLookup(...)
.How's that for a couple of simple LINQ queries?
当您使用 LINQ to Objects 时,此查询应该可以解决问题:
当
RewardTransactions
是IQueryable
时,您应该首先调用AsEnumerable()
关于它。When you're using LINQ to Objects, this query should do the trick:
When
RewardTransactions
however is anIQueryable
, you should first callAsEnumerable()
on it.为什么不这样做:
它不完全是 LINQ,而是直接的。我还稍微简化了您的 LINQ 查询;-)
Why not do it just like this:
It's not entirely LINQ, but straight forward. I also simplified your LINQ query a bit ;-)
我想如果您不使用匿名类型(var),而是创建自定义类型并在查询上执行 .ToList() ,您可以在列表上使用 .Add() 并将图表绑定到列表。
I guess If you do not use an anonymoustype(var), but create a custom type and do a .ToList() on your query that you can use .Add() on your list and bind the chart to the list.