Reputation: 139
I am looping through a list and insert these values into another object. However I have another list and if inv.id
and inv.name
match I need to update the amount
and qty
with the values from the other list. What is best approach?
//loop through Invoices
foreach (invoice inv in list1)
{
//if id and name match my other list(list2) I need to replace inv.amount and inv.qty with the values from the other list (list2.amount, list2.qty)
InsertAdditionalInvoice(inv.ID, inv.name, inv.address, inv.lot, inv.order,
inv.invoiceid, inv.amount, inv.qty);
}
}
it is not updating the values in the first list. I have a method that returns the list then call it with following code:
var list2 = GetInivoice2();
I then call this list as follows in the foreach loop:
var listtmp = list2.FirstOrDefault(o => o.ID == inv.ID && o.name == inv.name );
if (listtmp != null)
{
req.Quantity = Convert.ToDouble(listtmp.Quantity);
here is list method that returns my list(names are different):
public List GetInvoice2() {
List<inv2> inv2s = new List<inv2>();
Database db = DatabaseFactory.CreateDatabase("tmp");
DbCommand cmd = db.GetStoredProcCommand("getinv2");
using (IDataReader reader = db.ExecuteReader(cmd))
{
while (reader.Read())
{
inv2.Add(new inv2
{
InvoiceID = Convert.ToInt32(reader["InvoiceID"]),
InvoiceName = reader["InvoiceName"].ToString(),
Quantity = Convert.ToDecimal(reader["Quantity"]),
});
}
}
return inv2;
}
Upvotes: 0
Views: 1626
Reputation: 89285
This one will work i think
//if id and name match my other list(list2) I need to replace inv.amount and inv.qty with the values from the other list (list2.amount, list2.qty)
var q = list2.FirstOrDefault(o => o.ID == inv.ID && o.name == inv.name);
if (q != null)
{
inv.amount = q.amount;
inv.qty = q.qty;
}
Add above codes before calling InsertAdditionalInvoice. I'm not sure if this is the best approach or not, but i usually do it this way.
Upvotes: 1
Reputation: 11964
Straight solution:
var l2value=list2.FirstOrDefault(l=>l.id==inv.id)
if(l2value!=null){
inv.amount=l2value.amount;
Inv.qty=l2value.qty;
}
Upvotes: 0