简体   繁体   English

linq检索名称而不是id并按降序列出

[英]linq to retrieve name instead of id and list in descending order

can u help me to solve this. 你能帮我解决这个问题吗? i'm retrieving the balance of each heads, and i retrieved the balance of each heads. 我正在检索每个头的余额,并且已检索每个头的余额。 Now i want to list the balance in the descending order and list the name instead of h_id. 现在,我想按降序列出余额,并列出名称而不是h_id。 i used the code 我用了代码

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

You need to use group join of heads with ledgers. 您需要将分类帐与组长组合使用。 It will give you access both to head entity and all related ledgers (in headLedgers collection): 它将使您可以访问总公司实体和所有相关分类帐(在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,
}

I also introduced two range variables for total credit and total debit (consider better names here) to avoid calculating them second time for balance. 我还为总贷方和总借方引入了两个范围变量(请在此处考虑更好的名称),以避免第二次计算余额。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM