我试图运行以下查询,但由于某种原因,MemberTransactionCount
和NonMemberTransactionCount
返回为完全相同的值。看来.Where()
条款并没有像我们期望的那样起作用。
希望有人能指出我可能出错的地方。
from trans in transactions
orderby trans.TransactionDate.Year , trans.TransactionDate.Month
group trans by new {trans.TransactionDate.Year, trans.TransactionDate.Month}
into grp
select new MemberTransactions
{
Month = string.Format("{0}/{1}", grp.Key.Month, grp.Key.Year),
MemberTransactionCount =
grp.Where(x => x.Account.Id != Guid.Empty || x.CardNumber != null)
.Sum(x => x.AmountSpent),
NonMemberTransactionCount =
grp.Where(x => x.Account.Id == Guid.Empty && x.CardNumber == null)
.Sum(x => x.AmountSpent)
}
编辑我已经在数据库中验证了结果不是他们应该有的。似乎是将所有内容加在一起,而没有考虑到我们正在查看的Account
标准。
我最终用两个单独的查询解决了这个问题。它不完全是我想要的,但它做的工作,似乎和我希望的一样快。
var memberTrans = from trans in transactions
where trans.Account != null
|| trans.CardNumber != null
orderby trans.TransactionDate.Month
group trans by trans.TransactionDate.Month
into grp
select new
{
Month = grp.Key,
Amount = grp.Sum(x => x.AmountSpent)
};
var nonMemberTrans = (from trans in transactions
where trans.Account == null
&& trans.CardNumber == null
group trans by trans.TransactionDate.Month
into grp
select new
{
Month = grp.Key,
Amount = grp.Sum(x => x.AmountSpent)
}).ToList();
var memberTransactions = new List<MemberTransactions>();
foreach (var trans in memberTrans)
{
var non = (from nt in nonMemberTrans
where nt.Month == trans.Month
select nt).FirstOrDefault();
var date = new DateTime(2012, trans.Month, 1);
memberTransactions.Add(new MemberTransactions
{
Month = date.ToString("MMM"),
MemberTransactionCount = trans.Amount,
NonMemberTransactionCount = non != null ? non.Amount : 0.00m
});
}
我认为这里的主要问题是你怀疑结果,尽管它可能是正确的。
为验证添加另一个属性:
TotalAmount = grp.Sum(x => x.AmountSpent)