From 7d489f1b3a232f559e34c27b6810fdb32272910b Mon Sep 17 00:00:00 2001 From: Prakhar Date: Wed, 16 Aug 2023 14:17:03 +0530 Subject: [PATCH 1/3] Day 2 Tasks --- week-1/day-2/exercise-1/Circle/Circle.cs | 17 ++ week-1/day-2/exercise-1/Circle/Program.cs | 12 +- .../day-2/exercise-2/BankAccount/Program.cs | 90 +++++++- .../exercise-3/AnimalExercise/Program.cs | 66 +++++- .../VehicleManagementSystem/Program.cs | 198 +++++++++++++++++- 5 files changed, 367 insertions(+), 16 deletions(-) diff --git a/week-1/day-2/exercise-1/Circle/Circle.cs b/week-1/day-2/exercise-1/Circle/Circle.cs index 065ffa5d..9d9e2fd1 100644 --- a/week-1/day-2/exercise-1/Circle/Circle.cs +++ b/week-1/day-2/exercise-1/Circle/Circle.cs @@ -9,5 +9,22 @@ namespace Circle internal class Circle { // Implement the Circle class here + public double Radius { get; private set; } + + public Circle(double radius) + { + Radius = radius; + } + + public double GetArea() + { + return Math.PI * Math.Pow(Radius, 2); + } + + public double GetCircumference() + { + return 2 * Math.PI * Radius; + } + } } diff --git a/week-1/day-2/exercise-1/Circle/Program.cs b/week-1/day-2/exercise-1/Circle/Program.cs index 0df91b0d..d7a5f941 100644 --- a/week-1/day-2/exercise-1/Circle/Program.cs +++ b/week-1/day-2/exercise-1/Circle/Program.cs @@ -4,7 +4,17 @@ internal class Program { static void Main(string[] args) { - // Create a Circle object and display its area and circumference + // Create a Circle object with a given radius + double radius = 5.0; + Circle circle = new Circle(radius); + + // Calculate and display the area + double area = circle.GetArea(); + Console.WriteLine($"Area of the circle with radius {radius}: {area}"); + + // Calculate and display the circumference + double circumference = circle.GetCircumference(); + Console.WriteLine($"Circumference of the circle with radius {radius}: {circumference}"); } } } \ No newline at end of file diff --git a/week-1/day-2/exercise-2/BankAccount/Program.cs b/week-1/day-2/exercise-2/BankAccount/Program.cs index c58c30e2..84f485ad 100644 --- a/week-1/day-2/exercise-2/BankAccount/Program.cs +++ b/week-1/day-2/exercise-2/BankAccount/Program.cs @@ -1,10 +1,90 @@ -namespace BankAccount +using System; + +public abstract class BankAccount { - internal class Program + public string AccountNumber { get; protected set; } + public double Balance { get; protected set; } + + public BankAccount(string accountNumber, double initialBalance) { - static void Main(string[] args) + AccountNumber = accountNumber; + Balance = initialBalance; + } + + public abstract void Deposit(double amount); + public abstract void Withdraw(double amount); +} + +public class SavingsAccount : BankAccount +{ + public double InterestRate { get; private set; } + + public SavingsAccount(string accountNumber, double initialBalance, double interestRate) + : base(accountNumber, initialBalance) + { + InterestRate = interestRate; + } + + public override void Deposit(double amount) + { + Balance += amount; + } + + public override void Withdraw(double amount) + { + if (Balance >= amount) + { + Balance -= amount; + } + else { - // Create SavingsAccount and CheckingAccount objects and perform operations + Console.WriteLine("Insufficient balance."); } } -} \ No newline at end of file +} + +public class CheckingAccount : BankAccount +{ + public double OverdraftLimit { get; private set; } + + public CheckingAccount(string accountNumber, double initialBalance, double overdraftLimit) + : base(accountNumber, initialBalance) + { + OverdraftLimit = overdraftLimit; + } + + public override void Deposit(double amount) + { + Balance += amount; + } + + public override void Withdraw(double amount) + { + if (Balance + OverdraftLimit >= amount) + { + Balance -= amount; + } + else + { + Console.WriteLine("Insufficient balance."); + } + } +} + +class Program +{ + static void Main(string[] args) + { + SavingsAccount savingsAccount = new SavingsAccount("SA123", 1000, 0.05); + CheckingAccount checkingAccount = new CheckingAccount("CA456", 500, 200); + + savingsAccount.Deposit(500); + savingsAccount.Withdraw(200); + + checkingAccount.Deposit(300); + checkingAccount.Withdraw(800); + + Console.WriteLine($"Savings Account Balance: {savingsAccount.Balance}"); + Console.WriteLine($"Checking Account Balance: {checkingAccount.Balance}"); + } +} diff --git a/week-1/day-2/exercise-3/AnimalExercise/Program.cs b/week-1/day-2/exercise-3/AnimalExercise/Program.cs index 5928b7cb..756e8b2c 100644 --- a/week-1/day-2/exercise-3/AnimalExercise/Program.cs +++ b/week-1/day-2/exercise-3/AnimalExercise/Program.cs @@ -1,10 +1,66 @@ -namespace AnimalExercise +using System; +using System.Collections.Generic; + +public abstract class Animal { - internal class Program + public string Name { get; set; } + public int Age { get; set; } + + public abstract void MakeSound(); +} + +public class Dog : Animal, IMovable +{ + public override void MakeSound() + { + Console.WriteLine("Woof"); + } + + public void Move() { - static void Main(string[] args) + Console.WriteLine("Dog is running."); + } +} + +public class Cat : Animal, IMovable +{ + public override void MakeSound() + { + Console.WriteLine("Meow"); + } + + public void Move() + { + Console.WriteLine("Cat is sneaking."); + } +} + +public interface IMovable +{ + void Move(); +} + +class Program +{ + static void Main(string[] args) + { + List animals = new List + { + new Dog { Name = "Buddy", Age = 3 }, + new Cat { Name = "Whiskers", Age = 2 } + }; + + foreach (var animal in animals) { - // Create a list of Animal objects, add Dog and Cat instances, and call their methods + Console.WriteLine($"Name: {animal.Name}, Age: {animal.Age}"); + animal.MakeSound(); + + if (animal is IMovable movableAnimal) + { + movableAnimal.Move(); + } + + Console.WriteLine(); } } -} \ No newline at end of file +} diff --git a/week-1/day-2/exercise-4/VehicleManagementSystem/Program.cs b/week-1/day-2/exercise-4/VehicleManagementSystem/Program.cs index 77395b3a..add6361c 100644 --- a/week-1/day-2/exercise-4/VehicleManagementSystem/Program.cs +++ b/week-1/day-2/exercise-4/VehicleManagementSystem/Program.cs @@ -1,10 +1,198 @@ -namespace VehicleManagementSystem +using System; +using System.Collections.Generic; + +// 1. IVehicle interface +public interface IVehicle { - internal class Program + void Drive(); +} + +// 2. Car and Truck classes +public class Car : IVehicle +{ + public void Drive() + { + Console.WriteLine("Car is driving."); + } +} + +public class Truck : IVehicle +{ + public void Drive() + { + Console.WriteLine("Truck is driving."); + } +} + +// 3. Singleton VehicleLogger class +public class VehicleLogger +{ + private static VehicleLogger instance; + private VehicleLogger() { } + + public static VehicleLogger Instance + { + get + { + if (instance == null) + { + instance = new VehicleLogger(); + } + return instance; + } + } + + public void Log(string message) + { + Console.WriteLine($"[Log] {message}"); + } +} + +// 4. Abstract VehicleFactory class +public abstract class VehicleFactory +{ + public abstract IVehicle CreateVehicle(); + + public void DoSomethingWithVehicle() + { + IVehicle vehicle = CreateVehicle(); + vehicle.Drive(); + } +} + +// 5. Concrete factory classes +public class CarFactory : VehicleFactory +{ + public override IVehicle CreateVehicle() + { + return new Car(); + } +} + +public class TruckFactory : VehicleFactory +{ + public override IVehicle CreateVehicle() + { + return new Truck(); + } +} + +// 6. IRepository interface +public interface IRepository +{ + T GetById(int id); + IEnumerable GetAll(); + void Add(T entity); + void Update(T entity); + void Delete(T entity); +} + +// 7. VehicleRepository class +public class VehicleRepository : IRepository +{ + private List vehicles = new List(); + + public IVehicle GetById(int id) + { + return vehicles.FirstOrDefault(v => v.GetHashCode() == id); + } + + public IEnumerable GetAll() + { + return vehicles; + } + + public void Add(IVehicle entity) + { + vehicles.Add(entity); + } + + public void Update(IVehicle entity) + { + // Implement update logic + } + + public void Delete(IVehicle entity) + { + vehicles.Remove(entity); + } +} + +// 8. VehicleService class +public class VehicleService +{ + private IRepository repository; + private VehicleLogger logger; + + public VehicleService(IRepository repository) + { + this.repository = repository; + logger = VehicleLogger.Instance; + } + + public void AddVehicle(VehicleFactory factory) { - static void Main(string[] args) + IVehicle vehicle = factory.CreateVehicle(); + repository.Add(vehicle); + logger.Log($"Added a new {vehicle.GetType().Name}"); + } + + public void RemoveVehicle(int id) + { + IVehicle vehicle = repository.GetById(id); + if (vehicle != null) + { + repository.Delete(vehicle); + logger.Log($"Removed {vehicle.GetType().Name}"); + } + else { - Console.WriteLine("Hello, World!"); + logger.Log("Vehicle not found."); } } -} \ No newline at end of file + + public void ListVehicles() + { + foreach (var vehicle in repository.GetAll()) + { + Console.WriteLine($"Vehicle: {vehicle.GetType().Name}"); + } + } + + public void DoSomethingWithVehicle(int id) + { + IVehicle vehicle = repository.GetById(id); + if (vehicle != null) + { + vehicle.Drive(); + logger.Log($"Performed action on {vehicle.GetType().Name}"); + } + else + { + logger.Log("Vehicle not found."); + } + } +} + +class Program +{ + static void Main(string[] args) + { + IRepository repository = new VehicleRepository(); + VehicleService service = new VehicleService(repository); + + VehicleFactory carFactory = new CarFactory(); + VehicleFactory truckFactory = new TruckFactory(); + + service.AddVehicle(carFactory); + service.AddVehicle(truckFactory); + + service.ListVehicles(); + + service.DoSomethingWithVehicle(1); + service.DoSomethingWithVehicle(2); + + service.RemoveVehicle(1); + service.ListVehicles(); + } +} From c6446d520662ed3f0aeaf31c93904992a88a86cc Mon Sep 17 00:00:00 2001 From: Prakhar Date: Wed, 16 Aug 2023 15:29:12 +0530 Subject: [PATCH 2/3] Day 3 Tasks --- week-1/day-3/exercise-1/FactorialApp/Program.cs | 15 +++++++++++++-- .../exercise-2/ShortesPathAlgorithm/Program.cs | 2 +- 2 files changed, 14 insertions(+), 3 deletions(-) diff --git a/week-1/day-3/exercise-1/FactorialApp/Program.cs b/week-1/day-3/exercise-1/FactorialApp/Program.cs index f116eeca..aced81db 100644 --- a/week-1/day-3/exercise-1/FactorialApp/Program.cs +++ b/week-1/day-3/exercise-1/FactorialApp/Program.cs @@ -12,9 +12,20 @@ public static void Main() Console.WriteLine($"The factorial of {number} is: {factorial}"); } - public static long CalculateFactorial(int number) + public static long CalculateFactorial(int n ) { - throw new NotImplementedException(); + if (n == 0 || n == 1) + { + return 1; + } + + long result = 1; + for (int i = 2; i <= n; i++) + { + result *= i; + } + + return result; } } } \ No newline at end of file diff --git a/week-1/day-3/exercise-2/ShortesPathAlgorithm/Program.cs b/week-1/day-3/exercise-2/ShortesPathAlgorithm/Program.cs index a4ec62d9..8c02d7d6 100644 --- a/week-1/day-3/exercise-2/ShortesPathAlgorithm/Program.cs +++ b/week-1/day-3/exercise-2/ShortesPathAlgorithm/Program.cs @@ -223,7 +223,7 @@ public int[] DijkstraShortestPath(int source) visited[i] = false; } - distances[source] = int.MinValue; + distances[source] = 0; for (int count = 0; count < vertices - 1; count++) { From b06211faaf2f10095e841c1236d58619a6dc3a8d Mon Sep 17 00:00:00 2001 From: Prakhar Date: Wed, 16 Aug 2023 17:33:16 +0530 Subject: [PATCH 3/3] Day 4 Tasks --- .../day-4/exercise-1/StackApp/ICustomStack.cs | 29 ++++++++++-- week-1/day-4/exercise-1/StackApp/Program.cs | 47 ++++++++++++++++++- .../day-4/exercise-2/IteratorsApp/Program.cs | 12 ++++- .../exercise-3/LinqToObjectsApp/Program.cs | 36 ++++++++++++-- .../day-4/exercise-4/LinqToXmlApp/Program.cs | 23 ++++++++- .../QueryOptimizationApp/Program.cs | 22 ++++++++- .../exercise-6/LinqFilterAndSort/Program.cs | 27 ++++++++++- .../exercise-7/LinqListNumbers/Program.cs | 31 ++++++++++++ .../exercise-8/LinqGroupAggregate/Program.cs | 44 ++++++++++++++++- 9 files changed, 254 insertions(+), 17 deletions(-) diff --git a/week-1/day-4/exercise-1/StackApp/ICustomStack.cs b/week-1/day-4/exercise-1/StackApp/ICustomStack.cs index 55f3936d..5528015a 100644 --- a/week-1/day-4/exercise-1/StackApp/ICustomStack.cs +++ b/week-1/day-4/exercise-1/StackApp/ICustomStack.cs @@ -1,9 +1,30 @@ namespace StackApp { - internal interface ICustomStack + internal class ICustomStack { - void Push(T item); - T Pop(); - bool IsEmpty(); + private List items = new List(); + + public void Push(T item) + { + items.Add(item); + } + + public T Pop() + { + if (IsEmpty()) + { + throw new InvalidOperationException("Stack is empty."); + } + + int lastIndex = items.Count - 1; + T poppedItem = items[lastIndex]; + items.RemoveAt(lastIndex); + return poppedItem; + } + + public bool IsEmpty() + { + return items.Count == 0; + } } } diff --git a/week-1/day-4/exercise-1/StackApp/Program.cs b/week-1/day-4/exercise-1/StackApp/Program.cs index e089f665..b4ecbf9a 100644 --- a/week-1/day-4/exercise-1/StackApp/Program.cs +++ b/week-1/day-4/exercise-1/StackApp/Program.cs @@ -1,4 +1,6 @@ -namespace StackApp +using System; + +namespace StackApp { internal class Program { @@ -10,7 +12,48 @@ static void Main(string[] args) //intStack.Push(3); //Console.WriteLine(intStack.Pop()); // Output: 3 //Console.WriteLine(intStack.Pop()); // Output: 2 - //Console.WriteLine(intStack.IsEmpty()); // Output: False + //Console.WriteLine(intStack.IsEmpty()); // Output: + Stack intStack = new Stack(); + intStack.Push(10); + intStack.Push(20); + intStack.Push(30); + + Console.WriteLine("Popped: " + intStack.Pop()); // Output: Popped: 30 + Console.WriteLine("Popped: " + intStack.Pop()); // Output: Popped: 20 + + // Test with strings + Stack stringStack = new Stack(); + stringStack.Push("Hello"); + stringStack.Push("World"); + + Console.WriteLine("Popped: " + stringStack.Pop()); // Output: Popped: World + + // Test with custom objects + Stack personStack = new Stack(); + personStack.Push(new Person("Alice", 25)); + personStack.Push(new Person("Bob", 30)); + + Person poppedPerson = personStack.Pop(); + Console.WriteLine("Popped Person: " + poppedPerson); // Output: Popped Person: Name: Bob, Age: 30 } + + + class Person + { + public string Name { get; set; } + public int Age { get; set; } + + public Person(string name, int age) + { + Name = name; + Age = age; + } + + public override string ToString() + { + return $"Name: {Name}, Age: {Age}"; + } + } + } } \ No newline at end of file diff --git a/week-1/day-4/exercise-2/IteratorsApp/Program.cs b/week-1/day-4/exercise-2/IteratorsApp/Program.cs index f3cb1ae8..64c7d21a 100644 --- a/week-1/day-4/exercise-2/IteratorsApp/Program.cs +++ b/week-1/day-4/exercise-2/IteratorsApp/Program.cs @@ -14,7 +14,17 @@ static void Main(string[] args) // https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/statements/yield public static IEnumerable FibonacciSequence() { - throw new NotImplementedException(); + int current = 0; + int next = 1; + + for (int i = 0; i < int.MaxValue; i++) + { + yield return current; + + int temp = current; + current = next; + next = temp + next; + } } } } \ No newline at end of file diff --git a/week-1/day-4/exercise-3/LinqToObjectsApp/Program.cs b/week-1/day-4/exercise-3/LinqToObjectsApp/Program.cs index 95e8ac84..3162bac6 100644 --- a/week-1/day-4/exercise-3/LinqToObjectsApp/Program.cs +++ b/week-1/day-4/exercise-3/LinqToObjectsApp/Program.cs @@ -13,11 +13,37 @@ static void Main(string[] args) }; - //Write queries using LINQ for following operations - //1. Get all people from USA - //2. Get all people above 30 - //3. Sort people by name - //4. Project/Select only Name and Country of all people + // 1. Get all people from USA + var peopleFromUSA = people.Where(person => person.Country == "USA"); + Console.WriteLine("People from USA:"); + foreach (var person in peopleFromUSA) + { + Console.WriteLine($"{person.Name}, Age: {person.Age}, Country: {person.Country}"); + } + + // 2. Get all people above 30 + var peopleAbove30 = people.Where(person => person.Age > 30); + Console.WriteLine("\nPeople above 30:"); + foreach (var person in peopleAbove30) + { + Console.WriteLine($"{person.Name}, Age: {person.Age}, Country: {person.Country}"); + } + + // 3. Sort people by name + var sortedPeopleByName = people.OrderBy(person => person.Name); + Console.WriteLine("\nPeople sorted by name:"); + foreach (var person in sortedPeopleByName) + { + Console.WriteLine($"{person.Name}, Age: {person.Age}, Country: {person.Country}"); + } + + // 4. Project/Select only Name and Country of all people + var projectedPeople = people.Select(person => new { person.Name, person.Country }); + Console.WriteLine("\nProjected list with Name and Country properties:"); + foreach (var person in projectedPeople) + { + Console.WriteLine($"{person.Name}, Country: {person.Country}"); + } } } diff --git a/week-1/day-4/exercise-4/LinqToXmlApp/Program.cs b/week-1/day-4/exercise-4/LinqToXmlApp/Program.cs index 315df143..17e47a74 100644 --- a/week-1/day-4/exercise-4/LinqToXmlApp/Program.cs +++ b/week-1/day-4/exercise-4/LinqToXmlApp/Program.cs @@ -1,4 +1,6 @@ -namespace LinqToXmlApp +using System.Xml.Linq; + +namespace LinqToXmlApp { internal class Program { @@ -38,6 +40,25 @@ static void Main(string[] args) // Write the title of all books with genre "Genre 1" to the console + // Create an XDocument object from the XML string + XDocument bookDocument = XDocument.Parse(xmlString); + + // Write the title of all books to the console + Console.WriteLine("Titles of all books:"); + foreach (var book in bookDocument.Descendants("Book")) + { + Console.WriteLine(book.Element("Title").Value); + } + + // Write the title of all books with genre "Genre 1" to the console + Console.WriteLine("\nTitles of books with genre 'Genre 1':"); + var genre1Books = bookDocument.Descendants("Book") + .Where(book => book.Element("Genre").Value == "Genre 1"); + + foreach (var book in genre1Books) + { + Console.WriteLine(book.Element("Title").Value); + } } } } \ No newline at end of file diff --git a/week-1/day-4/exercise-5/QueryOptimizationApp/Program.cs b/week-1/day-4/exercise-5/QueryOptimizationApp/Program.cs index b18cea78..3f51ac7e 100644 --- a/week-1/day-4/exercise-5/QueryOptimizationApp/Program.cs +++ b/week-1/day-4/exercise-5/QueryOptimizationApp/Program.cs @@ -15,7 +15,8 @@ static void Main(string[] args) // Optimized implementation sw.Restart(); - + var optimizedQuery = GetTopLargerNumbers(data, 10, 100); + sw.Stop(); Console.WriteLine("Optimized Query: {0} ms", sw.ElapsedMilliseconds); } @@ -33,5 +34,24 @@ static List GenerateRandomNumbers(int count) return numbers; } + + // Optimized method to get top 'count' numbers larger than 'threshold' + static List GetTopLargerNumbers(List data, int count, int threshold) + { + List result = new List(count); + + foreach (int num in data) + { + if (num > threshold) + { + result.Add(num); + if (result.Count == count) + break; + } + } + + return result; + } + } } \ No newline at end of file diff --git a/week-1/day-4/exercise-6/LinqFilterAndSort/Program.cs b/week-1/day-4/exercise-6/LinqFilterAndSort/Program.cs index 5c6d6240..e6da4442 100644 --- a/week-1/day-4/exercise-6/LinqFilterAndSort/Program.cs +++ b/week-1/day-4/exercise-6/LinqFilterAndSort/Program.cs @@ -1,12 +1,37 @@ -namespace LinqFilterAndSort +using System; + +namespace LinqFilterAndSort { internal class Program { static void Main(string[] args) { // Create a list of Person objects + List people = new List + { + new Person { FirstName = "John", LastName = "Doe", Age = 30 }, + new Person { FirstName = "Jane", LastName = "Smith", Age = 25 }, + new Person { FirstName = "Michael", LastName = "Johnson", Age = 40 }, + new Person { FirstName = "Emily", LastName = "Davis", Age = 28 } + }; + // Use LINQ to filter and sort the list + var filteredAndSorted = people + .Where(person => person.Age >= 30) // Filter people with age >= 30 + .OrderBy(person => person.LastName) // Sort by last name + .ThenBy(person => person.FirstName); // Then sort by first name + // Print the filtered and sorted list of people to the console + foreach (var person in filteredAndSorted) + { + Console.WriteLine($"{person.FirstName} {person.LastName}, Age: {person.Age}"); + } } } + public class Person + { + public string FirstName { get; set; } + public string LastName { get; set; } + public int Age { get; set; } + } } \ No newline at end of file diff --git a/week-1/day-4/exercise-7/LinqListNumbers/Program.cs b/week-1/day-4/exercise-7/LinqListNumbers/Program.cs index 6caadd07..43490f6c 100644 --- a/week-1/day-4/exercise-7/LinqListNumbers/Program.cs +++ b/week-1/day-4/exercise-7/LinqListNumbers/Program.cs @@ -8,11 +8,42 @@ static void Main(string[] args) List numbers = new List { 5, 10, 15, 20, 25, 30, 35, 40, 45, 50 }; // Use LINQ to perform the following operations: + // 1. Find all even numbers + var evenNumbers = numbers.Where(num => num % 2 == 0); + // 2. Find all numbers greater than a specific value (e.g., 20) + int specificValue = 20; + var greaterThanSpecificValue = numbers.Where(num => num > specificValue); + // 3. Calculate the sum of all numbers + int sum = numbers.Sum(); + // 4. Calculate the average of all numbers + double average = numbers.Average(); + // 5. Find the minimum and maximum values in the list + int minValue = numbers.Min(); + int maxValue = numbers.Max(); + + // Print the results + Console.WriteLine("Even numbers:"); + foreach (var num in evenNumbers) + { + Console.WriteLine(num); + } + + Console.WriteLine("\nNumbers greater than " + specificValue + ":"); + foreach (var num in greaterThanSpecificValue) + { + Console.WriteLine(num); + } + + Console.WriteLine("\nSum of all numbers: " + sum); + Console.WriteLine("Average of all numbers: " + average); + + Console.WriteLine("\nMinimum value: " + minValue); + Console.WriteLine("Maximum value: " + maxValue); } } } \ No newline at end of file diff --git a/week-1/day-4/exercise-8/LinqGroupAggregate/Program.cs b/week-1/day-4/exercise-8/LinqGroupAggregate/Program.cs index 04dbd615..ae62bf0c 100644 --- a/week-1/day-4/exercise-8/LinqGroupAggregate/Program.cs +++ b/week-1/day-4/exercise-8/LinqGroupAggregate/Program.cs @@ -14,12 +14,52 @@ static void Main(string[] args) new Product { Name = "Jeans", Category = "Clothing", Price = 60.00M }, new Product { Name = "Sneakers", Category = "Footwear", Price = 100.00M } }; - // Use LINQ to perform the following operations: + // 1. Group products by category + var groupedProducts = products.GroupBy(product => product.Category); + // 2. Count the number of products in each category + var productCounts = groupedProducts.Select(group => new + { + Category = group.Key, + Count = group.Count() + }); + // 3. Calculate the total price of products in each category + var totalPriceByCategory = groupedProducts.Select(group => new + { + Category = group.Key, + TotalPrice = group.Sum(product => product.Price) + }); + // 4. Find the most expensive product in each category + var mostExpensiveProducts = groupedProducts.Select(group => new + { + Category = group.Key, + MostExpensiveProduct = group.OrderByDescending(product => product.Price).FirstOrDefault() + }); + + // Print the results + foreach (var count in productCounts) + { + Console.WriteLine($"Category: {count.Category}, Count: {count.Count}"); + } + + Console.WriteLine(); + + foreach (var total in totalPriceByCategory) + { + Console.WriteLine($"Category: {total.Category}, Total Price: {total.TotalPrice:C}"); + } + + Console.WriteLine(); + + foreach (var product in mostExpensiveProducts) + { + Console.WriteLine($"Category: {product.Category}, Most Expensive Product: {product.MostExpensiveProduct.Name}, Price: {product.MostExpensiveProduct.Price:C}"); + } } + } -} \ No newline at end of file +}