From c91591578dcad42582c9dc7eb90e9bc5d2dd9347 Mon Sep 17 00:00:00 2001 From: MarcUs7i <96580944+MarcUs7i@users.noreply.github.com> Date: Wed, 19 Mar 2025 22:02:13 +0100 Subject: [PATCH] Fixed Product.cs & implemented NonFood.cs --- Supermarket/NonFood.cs | 35 +++++++++++++++++++---------------- Supermarket/Product.cs | 24 ++++++++++++++++++++++-- 2 files changed, 41 insertions(+), 18 deletions(-) diff --git a/Supermarket/NonFood.cs b/Supermarket/NonFood.cs index 6835151..a502df0 100644 --- a/Supermarket/NonFood.cs +++ b/Supermarket/NonFood.cs @@ -9,32 +9,35 @@ public sealed class NonFood : Product public NonFood(string productName, string barcode, int quantity) : base(productName, barcode, quantity) { - // TODO - _reviews = null!; - Console.WriteLine($"Remove me, I just make code compile {_reviews}"); + _reviews = new List(); } - - // TODO - public Review[] Reviews => null!; + + public Review[] Reviews => _reviews.ToArray(); public double? AverageRating { get { - // TODO - return -1D; + if (_reviews.Count == 0) + { + return null; + } + + return _reviews.Average(review => (double)review.Rating); } } - - // TODO - protected override string[] CsvColumnNames => null!; - - // TODO - // hint: .ToString("F1", CultureInfo.InvariantCulture) - protected override string[] CsvColumnValues => null!; + + protected override string[] CsvColumnNames => ["Barcode", "ProductName", "Quantity", "AverageRating"]; + + protected override string[] CsvColumnValues => [ + Barcode, + ProductName, + Quantity.ToString("F0", CultureInfo.InvariantCulture), + AverageRating?.ToString("F1", CultureInfo.InvariantCulture) ?? String.Empty + ]; public void AddReview(Review review) { - // TODO + _reviews.Add(review); } } diff --git a/Supermarket/Product.cs b/Supermarket/Product.cs index cafa71e..1edf0fb 100644 --- a/Supermarket/Product.cs +++ b/Supermarket/Product.cs @@ -8,6 +8,10 @@ public abstract class Product protected Product(string productName, string barcode, int quantity) { + if (string.IsNullOrWhiteSpace(productName)) + { + productName = Invalid; + } ProductName = productName; Barcode = IsBarcodeValid(barcode) ? barcode : Invalid; Quantity = quantity > 0 ? quantity : 0; @@ -26,10 +30,18 @@ public abstract class Product public string GetCsvHeader() { string header = String.Empty; - foreach (var columnName in CsvColumnNames) + for (var i = 0; i < CsvColumnNames.Length; i++) { + string columnName = CsvColumnNames[i]; + + if(i == CsvColumnNames.Length - 1) + { + header += $"{columnName}"; + break; + } header += $"{columnName}{Separator}"; } + return header; } @@ -38,10 +50,18 @@ public abstract class Product protected static string ToCsvLine(string[] values, char separator) { string line = string.Empty; - foreach (var value in values) + for (var i = 0; i < values.Length; i++) { + string value = values[i]; + + if (i == values.Length - 1) + { + line += $"{value}"; + break; + } line += $"{value}{separator}"; } + return line; }