如何转换为 linq 请求
本文关键字:linq 请求 转换 何转换 | 更新日期: 2023-09-27 18:31:50
var list = new List<ListCreaditInBankView>();
var banktemp = m_banksRepository.Banks;
foreach (Bank bank in banktemp)
{
var bankbranchtemp = m_banksRepository.BankBranches.Where(x => x.BankId == bank.Id);
foreach (BankBranch bankBranch in bankbranchtemp)
{
var creditortemp = m_creditorsRepository.Creditors.Where(x => x.BankBranchId == bankBranch.Id);
list.Add(new ListCreaditInBankView(){Bank = bank, Creditors = creditortemp});
}
}
我需要在没有这些周期的情况下获得List<ListCreaditInBankView>
。
我试过了,但它只得到了一个Creditors
var lists = (from bank in banksTemp
let creditorBank = m_creditorsRepository.GetCreditorBank(bank.BankBranches.Select(x => x.Id).ToList())
select new ListCreaditInBankView() {Bank = bank, Creditors = creditorBank}).ToList();
尝试以下操作:
var lists = (from bank in m_banksRepository.Banks
select new ListCreaditInBankView
{
Bank = bank,
Creditors = creditorsRepository.GetCreditorBank(bank.BankBranches
.Select(x => x.Id).ToList())
}).ToList();
或者,如果您更喜欢另一种样式 LINQ(method chaining
它被称为,谢谢 Numan :)):
var lists = m_banksRepository.Banks
.Select(bank => new ListCreaditInBankView
{
Bank = bank,
Creditors = creditorsRepository.GetCreditorBank(bank.BankBranches
.Select(x => x.Id).ToList())
}).ToList();
如果您使用的是 Linq 2 实体框架,则可以尝试另一种方法。
http://msdn.microsoft.com/en-us/library/bb896272.aspx
您只需要确保已在数据库中正确设置了表和键(或至少在生成的模型中映射),否则它将不起作用。