简体   繁体   中英

iterate through two lists

I have the following models and lists

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

I want to filter the list List<.MCashTransactions> CashTransactions with property CashAccountId and id of list List<MCashAccount> CashAccounts

All I have done so far is to iterate and check on each iteration whether it exists or not. Any better way to achieve this with 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
              }
           }
        }

Yes, you can perform a join on two lists.

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() return only one item from the list (CashAccount), if exists more results - throw exception. If not result - return 0 - for structs, null - for reference type.

foreach(var q in query)
{
      //you can here use q.cashTransaction and object q.cashAccount/ q.cashAccount.Id
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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