遍历两个列表

时间:2014-07-19 18:57:45

标签: c# linq

我有以下型号和清单

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的属性CashAccountIdid过滤列表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
              }
           }
        }

2 个答案:

答案 0 :(得分:4)

是的,您可以在两个列表中执行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
}

答案 1 :(得分:0)

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
}