LINQ GROUPBY月,并添加任何缺少个月来的分组数据 [英] linq groupby Months and add any missing months to the grouped data
问题描述
我创建这似乎是工作确定一个LINQ声明。我可能会或maynot正确写它不过其返回我的预期结果。
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()
});
现在的结果返回由分组月5值。是否有可能与TransactionAmount = 0,将它们添加7个其他失踪月?
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?
原因我的疯狂是我想这些值绑定到一个图表,根据个月有我的X轴。目前其仅示出了5个月的记录。如果我的数据犯规一个月我一定要怎么在0值添加返回任意值。
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.
有什么建议?
推荐答案
如果你使用它很简单 .ToLookup(...)
。
var lookup =
(from w in RewardTransctions
where w.EntryType == 1
select w).ToLookup(w => w.PurchaseDate.Value.Month);
var grouped =
from m in Enumerable.Range(1, 12)
select new TransactionDetail()
{
Month = m,
TransactionAmount = lookup[m].Count(),
};
是如何形成的几个简单的LINQ查询的?
How's that for a couple of simple LINQ queries?
这篇关于LINQ GROUPBY月,并添加任何缺少个月来的分组数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!