Skip to main content
 首页 » 编程设计

c#之遍历两个列表

2024年02月06日14zengkefu

我有以下模型和列表

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<.MCashTransactions> CashTransactions有属性(property)CashAccountId和 id列表List<MCashAccount> CashAccounts

到目前为止,我所做的就是迭代并检查每次迭代是否存在。使用 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 
              } 
           } 
        } 

请您参考如下方法:

是的,您可以执行 join在两个列表上。

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 
}