How to return a list from a public function in C#

1 Answer

0 votes
using System;
using System.Collections.Generic;
using System.Linq;

namespace ListReturnExample
{
    /// <summary>
    /// Represents a simple product.
    /// </summary>
    public class Product
    {
        /// <summary>
        /// Gets or sets the product name.
        /// </summary>
        public string Name { get; set; } = string.Empty;

        /// <summary>
        /// Gets or sets the product price.
        /// </summary>
        public decimal Price { get; set; }
    }

    /// <summary>
    /// Provides product-related operations.
    /// </summary>
    public class ProductService
    {
        /// <summary>
        /// Returns all products whose price is greater than or equal
        /// to the specified minimum price.
        /// </summary>
        /// <param name="minPrice">
        /// The minimum price that a product must have to be included.
        /// </param>
        /// <returns>
        /// A list of matching products.
        /// </returns>
        /// <exception cref="ArgumentOutOfRangeException">
        /// Thrown when minPrice is negative.
        /// </exception>
        public List<Product> GetProductsByMinimumPrice(decimal minPrice)
        {
            if (minPrice < 0) {
                throw new ArgumentOutOfRangeException(
                    nameof(minPrice),
                    "Minimum price cannot be negative.");
            }

            var products = new List<Product>
            {
                new Product { Name = "Laptop", Price = 1200m },
                new Product { Name = "Mouse", Price = 25m },
                new Product { Name = "Keyboard", Price = 80m },
                new Product { Name = "Monitor", Price = 300m }
            };

            return products
                .Where(product => product.Price >= minPrice)
                .ToList();
        }
    }

    internal class Program
    {
        private static void Main()
        {
            var productService = new ProductService();

            List<Product> expensiveProducts =
                productService.GetProductsByMinimumPrice(100m);

            foreach (Product product in expensiveProducts) {
                Console.WriteLine(
                    $"{product.Name} - ${product.Price}");
            }
        }
    }
}


/*
run:

Products found:
Laptop - $1200
Monitor - $300

*/

 



answered Oct 1 by avibootz

Related questions

1 answer 216 views
1 answer 184 views
184 views asked Sep 9, 2020 by avibootz
1 answer 231 views
231 views asked Aug 21, 2018 by avibootz
1 answer 222 views
222 views asked Jan 1, 2017 by avibootz
1 answer 233 views
233 views asked Jan 1, 2017 by avibootz
...