Linq语法连接和组

时间:2011-08-23 03:21:52

标签: linq join syntax linq-group

你好我需要加入两个表(MainTransaction和Subtransaction),这里的问题是我也想获得MainTransaction的所有记录,而不是在Subtransaction中,我被困在这个部分,我怎么能实现这个?

protected object SelectMainTbl()
{
    var mainIdAndSum = from st in t.subtransaction
                       group st by st.MainTransactionId into g
                       select new
                       {
                           Sum = (from r in g
                                  select r.Amount).Sum(),
                           MainId = g.Key
                       };

    var mainTbl = from main in t.maintransaction
                  join sub in mainIdAndSum on main.MainTransactionId equals sub.MainId
                  where main.IsEnabled == true && (sub.Sum - main.Amount != 0)
                  select main;

    return mainTbl;
}

1 个答案:

答案 0 :(得分:1)

我认为这是您想要的查询:

from mt in t.maintransaction
join st in t.subtransaction
    on mt.MainTransactionId equals st.MainTransactionId
    into sts
where mt.IsEnabled
where sts.Sum(x => x.Amount) - mt.Amount != 0
select new
{
    MainTransaction = mt,
    Subtransactions = sts,
};