LINQ 查询显示 2 个表的结果

LINQ query to show result of 2 tables

这是我的两个 table

BuyShare

SoldShare

我想从 LINQ 查询得到的结果 table 是

此结果table 包含公司名称以及总买卖股份。

到目前为止我的代码是:

var userHistoryAll = from buy in db.share_bought_history
                     join sold in db.share_sold_history
                     on buy.regist_id equals sold.regist_id
                     select new
                             {
                                 buy,
                                 sold
                             } into combine
                     group combine by combine.buy.comapnay_id
                     into final
                     select new
                             {
                                 cName = final.FirstOrDefault().buy.company.company_name,
                                 uBuy = final.Sum(x => x.buy.no_of_sahre),
                                 uSold = final.Sum(x => x.sold.no_of_sahre)
                             };

但我得不到想要的结果。

尝试以下操作:

var userHistoryAll = (from buy in db.share_bought_history
                                 join sold in db.share_sold_history
                                 on buy.comapnay_id equals sold.comapnay_id
                                 select new { buy = buy, sold = sold})
                                 .GroupBy(x => x.buy.comapnay_id)
                                 .Select(x => new {
                                     cName=x.Key,
                                     uBuy = x.Select(y => y.buy.no_of_sahre).Sum(),
                                     uSold = final.Select(y => y.sold.no_of_sahre).Sum()
                                 }).ToList(); 

问题是您的数据没有唯一的键可以加入(至少我是这么认为的)

所以先做 groub 然后加入

我个人更喜欢 lambda 语法,但您可以对其进行转换

var buyGroub = BuyShare.GroubBy(x=>x.Id)
                       .Select(x=> new 
                       {
                          name = x.Name,
                          buy = x.Sum(s => s.Share)
                       }

var soldGroub = SoldShare.GroubBy(x=>x.Id)
                       .Select(x=> new 
                       {
                          name = x.Name,
                          sold = x.Sum(s => s.Share)
                       }

现在您可以随心所欲地展示

var result = buyGroub.Join(soldGroub,
                          a=>a.name,
                          b=>b.name,
                          (a,b)=>new {a.Name , a.buy , b.sold});

编辑

要获取 list1 中而不是 list2 中的记录,反之则需要执行一个名为 full outer join 的操作。检查已接受的答案,它有两个等效于你的 2 个列表