LINQ group with with count的问题

时间:2013-01-09 15:18:52

标签: c# linq fluent-nhibernate

我正在尝试运行以下查询,但出于某种原因,MemberTransactionCountNonMemberTransactionCount将返回完全相同的值。似乎.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条件。

2 个答案:

答案 0 :(得分:1)

我最后用两个单独的查询来解决这个问题。这不是我想要的,但是它完成了工作,似乎和我希望的一样快。

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
    });
}

答案 1 :(得分:0)

我认为这里的主要问题是你怀疑结果,尽管它可能是正确的。

添加另一个属性进行验证:

TotalAmount = grp.Sum(x => x.AmountSpent)