-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path5.2.Testing.cs
More file actions
110 lines (88 loc) · 2.72 KB
/
5.2.Testing.cs
File metadata and controls
110 lines (88 loc) · 2.72 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
using System;
using System.Collections.Generic;
using System.Linq;
public class ShoppingCart
{
public class CartItem
{
public int ProductId { get; set; }
public string ProductName { get; set; }
public decimal Price { get; set; }
public int Quantity { get; set; }
}
private List<CartItem> items;
public ShoppingCart()
{
items = new List<CartItem>();
}
public void AddItem(int productId, string productName, decimal price, int quantity)
{
var existingItem = items.FirstOrDefault(item => item.ProductId == productId);
if (existingItem != null)
{
existingItem.Quantity += quantity;
}
else
{
var newItem = new CartItem
{
ProductId = productId,
ProductName = productName,
Price = price,
Quantity = quantity
};
items.Add(newItem);
}
}
public void UpdateQuantity(int productId, int quantity)
{
var existingItem = items.FirstOrDefault(item => item.ProductId == productId);
if (existingItem != null)
{
existingItem.Quantity = quantity;
}
}
public void RemoveItem(int productId)
{
var itemToRemove = items.FirstOrDefault(item => item.ProductId == productId);
if (itemToRemove != null)
{
items.Remove(itemToRemove);
}
}
public decimal CalculateTotal()
{
return items.Sum(item => item.Price * item.Quantity);
}
public List<CartItem> GetCartItems()
{
return items.ToList();
}
}
class Program
{
static void Main()
{
var shoppingCart = new ShoppingCart();
shoppingCart.AddItem(1, "Product A", 25.99m, 2);
shoppingCart.AddItem(2, "Product B", 15.49m, 3);
Console.WriteLine("Cart Contents:");
foreach (var item in shoppingCart.GetCartItems())
{
Console.WriteLine($"{item.ProductName} - Quantity: {item.Quantity} - Price: {item.Price:C}");
}
Console.WriteLine($"Total Price: {shoppingCart.CalculateTotal():C}");
shoppingCart.UpdateQuantity(1, 5);
Console.WriteLine("\nUpdated Cart Contents:");
foreach (var item in shoppingCart.GetCartItems())
{
Console.WriteLine($"{item.ProductName} - Quantity: {item.Quantity} - Price: {item.Price:C}");
}
shoppingCart.RemoveItem(2);
Console.WriteLine("\nCart Contents After Removing Item:");
foreach (var item in shoppingCart.GetCartItems())
{
Console.WriteLine($"{item.ProductName} - Quantity: {item.Quantity} - Price: {item.Price:C}");
}
}
}