Reputation: 1023
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
}
}
}
Upvotes: 1
Views: 109
Reputation: 1776
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
}
Upvotes: 0
Reputation: 73442
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
}
Upvotes: 4