LINQ 检索名称而不是 ID 并按降序列出
本文关键字:降序 ID 检索 LINQ | 更新日期: 2023-09-27 18:35:10
你能帮我解决这个问题吗?我正在检索每个头部的余额,我检索了每个头部的余额。现在我想按降序列出余额并列出名称而不是h_id。 我使用了代码
protected void account_watchlist() {
using(var context = new sem_dbEntities()) {
//ledger && head
var year = DateTime.Now.AddMinutes(318).Year;
var month = DateTime.Now.AddMinutes(318).Month;
var start = new DateTime();
if (month >= 4) {
start = new DateTime(year, 04, 01);
} else if (month < 4) {
start = new DateTime(year - 1, 04, 01);
}
var qr = (from a in context.ledgers
where a.entry_date >= start && a.entry_date < new DateTime(year, month, 1)
join b in context.heads on a.h_id equals b.h_id
group a by a.h_id into sb select new {
sb.FirstOrDefault().h_id,
totalc = sb.Sum(c => c.credit),
totald = sb.Sum(d => d.debit),
balance = sb.Sum(d => d.debit) - sb.Sum(c => c.credit)
}).ToList();
Repeater2.DataSource = qr.ToList();
Repeater2.DataBind();
}
}
您需要将头部的组连接与账本一起使用。它将使您能够访问头部实体和所有相关分类账(在 headLedgers 集合中):
from h in context.heads
join l in context.ledgers.Where(x => x.entry_date >= startDate && x.entry_date < endDate)
on h.h_id equals l.h_id into headLedgers
where headLedgers.Any()
let totalc = headLedgers.Sum(l => l.credit),
let totald = headLedgers.Sum(l => l.debit),
select new {
h.h_id,
h.name,
totalc,
totald,
balance = totald - totalc,
}
我还引入了总贷方和总借方的两个范围变量(在这里考虑更好的名称),以避免第二次计算它们的余额。