How to perform an update using Linq or Lambda?(C#,

2019-07-20 05:16发布

问题:

How can I do an update in Linq

My code is

List<Cart> objNewCartItems = (List<Cart>)Session["CartItems"];

            if ((objNewCartItems != null) && (objNewCartItems.Count > 0))
            {
                for (int i = 0; i < dgShoppingCart.Rows.Count; i++)
                {
                    Cart c = new Cart();
                    TextBox t = (TextBox)dgShoppingCart.Rows[i].FindControl("txtQuantity");
                    c.Quantity = (t.Text == string.Empty? (int?)null: Convert.ToInt32(t.Text));

                    objNewCartItems[i].Quantity = c.Quantity;
                }
            }
            Session["CartItems"] = objNewCartItems;            
            Response.Redirect("ItemListing.aspx", false);

Basically in the Cart Collection, there is an item called an Quantity which will be populated when the user will fill that.

So I am reading the Grid item and updating the Quantity attribute.

But I am sure that there must be a better way via linq or lambda to do the same.

Please help

Thanks in advance

回答1:

Well, you could replace one for loop with a foreach loop, or maybe use the List<T>.ForEach that does the same internally, but ultimately LINQ is a query syntax (hence the Q), not a mutation syntax, and it isn't usually very beneficial to try to represent the updates via an anonymous method (/lambda).

Note that .NET 4.0 introduces Expression nodes that allow better support for mutation, but the C# compiler doesn't add any support for them, so Expression lambdas are still limited to query (at least, via the language).

In short: maybe stick with what you have. You could add some LINQ here, but it would radically change the code in the same way that it can for some queries, so I don't see the benefit.



回答2:

try this:

int interator = 0;

List<Cart> objNewCartItems = (List<Cart>)Session["CartItems"];

objNewCartItems.ForEach( i => i.Quantity = GetCartQuantity(interator++));

Session["CartItems"] = objNewCartItems;            
Response.Redirect("ItemListing.aspx", false);

private int GetCartQuantity(int interator)
{
  if ((objNewCartItems != null) && (objNewCartItems.Count > 0))
  {
    Cart c = new Cart();
    TextBox t = (TextBox)dgShoppingCart.Rows[interator].FindControl("txtQuantity");
    c.Quantity = (t.Text == string.Empty? (int?)null: Convert.ToInt32(t.Text));
    return c.Quantity;                
  }
}