遍历两个列表
本文关键字:两个 列表 遍历 | 更新日期: 2023-09-27 18:13:53
我有以下型号和列表
public class MCashTransactions
{
public int id { get; set; }
public int CashAccountId { get; set; }
}
public class MCashAccount
{
public int id { get; set; }
}
List<MCashTransactions> CashTransactions = new List<.MCashTransactions>();
List<MCashAccount> CashAccounts = new List<MCashAccount>();
我想用列表List<MCashAccount> CashAccounts
的属性CashAccountId
和id
过滤列表List<.MCashTransactions> CashTransactions
到目前为止,我所做的只是迭代并检查每个迭代是否存在。有什么更好的方法可以用linq实现这一点吗?
for (int i = 0; i < CashTransactions.Count; i++)
{
for (int j = 0; j < CashAccounts.Count; j++)
{
if (CashTransactions[i].CashAccountId==CashAccounts[i].id)
{
//work to be done here
}
}
}
是的,您可以对两个列表执行联接。
var joined = from ct in CashTransactions
join ca in CashAccounts
on ct.CashAccountId equals ca.id
select new { CashTransaction = ct, CashAccount = ca };
foreach (var item in joined)
{
//Do whatever with item.CashAccount and item.CashTransaction
}
var query = from ct in CashTransactions
select new
{
cashTransaction = ct,
cashAccount = CashAccounts.Where(p=>p.id == ct.CashAccountId).SingleOrDefault()
};
SingleOrDefault((只返回列表中的一项(CashAccount(,如果存在更多结果,则抛出异常。如果不是结果-返回0-用于结构,null-用于引用类型。
foreach(var q in query)
{
//you can here use q.cashTransaction and object q.cashAccount/ q.cashAccount.Id
}