1

我有一个像下面这样的方法,有什么方法可以重构,更清洁的方法,这样我就可以用更少的代码行来实现它,例如删除 if / for 循环类似的东西

public void CheckProductExistThenAddToCart(CartItem item)
{
    if (CartItems.Count == 0) AddToCart(item);

    bool itemFound = false;
    foreach (var cartItem in CartItems)
    {
        if (cartItem.ProductId.Equals(item.ProductId))
        {
            itemFound = true;
            cartItem.Qty += item.Qty;
            break;
        }
    }

    if (!itemFound)
    {
        AddToCart(item);
    }
}
4

4 回答 4

6

您可以使用 LINQ:

public void CheckProductExistThenAddToCart(CartItem item)
{
     var existingItem = CartItems.FirstOrDefault(ci => ci.ProductID == item.ProductId);
     if (existingItem == null)
          CartItems.Add(item);
     else
          existingItem.Qty += item.Qty;
}
于 2013-08-31T23:07:08.393 回答
6

如果应该确保SingleOrDefault拥有独特的项目(在 的上下文中),您可以使用。ProductId如果可能有多个并且您想忽略这一事实,则更改为FirstOrDefault. 我发现Single更好,因为它在这里明确说明了意图。

public void CheckProductExistThenAddToCart(CartItem item)
{
  var existingItem = CartItems
      .SingleOrDefault(i => i.ProductId.Equals(item.ProductId));

  if (existingItem == null)
  {
    AddToCart(item);
  }
  else
  {
    existingItem.Qty += item.Qty;
  }
}
于 2013-08-31T23:07:59.237 回答
4

为了缩短此功能,您可以考虑使用

Dictionary<ProductId, CartItem> dict;

然后不用循环购物车,只需使用

if (dict.ContainsKey(productId))
{
    // add qty
} else {
    // add item to cart
}
于 2013-08-31T23:10:05.233 回答
1

首先,有一个错误,因为您在添加缺少的项目后没有返回。因此,您添加Qty到之前添加的同一项目,因此它的价值翻了一番。

所以而不是:

public void CheckProductExistThenAddToCart(CartItem item)
{
    if (CartItems.Count == 0) AddToCart(item);
    // missing return

    bool itemFound = false;
    foreach (var cartItem in CartItems)
    {
        if (cartItem.ProductId.Equals(item.ProductId))
        {
            itemFound = true; // ypu will find the same item you have justb added
            // ... causes this bug and is less efficient
            cartItem.Qty += item.Qty;
            ...

我会做(也用 Linq 简化):

public void CheckProductExistThenAddToCart(CartItem item)
{
    if (CartItems.Count == 0) 
    {
        AddToCart(item);
        return;
    }

    CartItem oldItem = CartItems.FirstOrDefault(ci => ci.ProductId == item.ProductId);
    if(oldItem == null)
        AddToCart(item);
    else
        oldItem.Qty += item.Qty;
}
于 2013-08-31T23:14:39.363 回答