【问题标题】:Modify List within foreach loop with value from another list使用来自另一个列表的值修改 foreach 循环中的列表
【发布时间】:2014-08-23 00:29:58
【问题描述】:

我正在遍历一个列表并将这些值插入到另一个对象中。但是我有另一个列表,如果 inv.idinv.name 匹配,我需要使用另一个列表中的值更新 amountqty。什么是最好的方法?

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

 }
}

它不会更新第一个列表中的值。我有一个返回列表的方法,然后使用以下代码调用它:

var list2 = GetInivoice2(); 

然后我在 foreach 循环中按如下方式调用此列表:

var listtmp = list2.FirstOrDefault(o => o.ID == inv.ID && o.name == inv.name );
if (listtmp != null)
{
req.Quantity = Convert.ToDouble(listtmp.Quantity);

这是返回我的列表的列表方法(名称不同):

公共列表 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;

    }

【问题讨论】:

  • 你的问题很不清楚。好吧,如果您需要在另一个列表中找到一些值,那就搜索它们吧!

标签: c# list foreach


【解决方案1】:

我认为这个可以工作

//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;
}

在调用 InsertAdditionalInvoice 之前添加上述代码。我不确定这是否是最好的方法,但我通常这样做。

【讨论】:

  • 或者只是:var q = list2.FirstOrDefault(o => o.ID == inv.ID && o.name == inv.name);
  • 它没有更新第一个列表中的值。我有一个返回列表的方法,然后使用以下代码调用它: var list2 = GetInivoice2();然后我在 foreach 循环中按如下方式调用此列表: var listtmp = list.FirstOrDefault(o => o.ID == inv.ID && o.name == inv.name ); if (listtmp != null) { req.Quantity = Convert.ToDouble(listtmp.Quantity); }
  • 如果你在 if(q != null) 中设置断点,你的程序是否曾经遇到过断点?
【解决方案2】:

直解:

var l2value=list2.FirstOrDefault(l=>l.id==inv.id)
if(l2value!=null){
    inv.amount=l2value.amount;
    Inv.qty=l2value.qty;
}

【讨论】:

    猜你喜欢
    • 2011-09-11
    • 1970-01-01
    • 2012-07-09
    • 1970-01-01
    • 2015-02-12
    • 1970-01-01
    • 2022-01-06
    • 2014-08-25
    • 2019-05-08
    相关资源
    最近更新 更多