这是我的两张桌子
BuyShare
SoldShare
我想从LINQ查询得到的结果表是
此结果表包含公司名称,其中包含总买入和卖出股票。
到目前为止,我的代码是:
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)
};
但我无法得到理想的结果。
答案 0 :(得分:1)
请尝试以下操作:
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();
答案 1 :(得分:1)
问题是您的数据没有唯一的加入密钥(至少我的意见)
所以首先通过加入
制作组合我个人喜欢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列表