foreach
class Program
    {
        static void Main(string[] args)
        {
            var products = new Product[]{ 
                                        new Product(){Name="Kayak" , Price=9.5M},
                                        new Product(){Name="Lifejacket" , Price=48.95M},
                                        new Product(){Name="Scooceer ball" , Price=19.5M},
                                        new Product(){Name="Stadium" , Price=79550M}
                                    };
            ForeachCheck(products);
            var sum = ForeachSum(products);
            Console.WriteLine(sum);
            Console.Read();
        }
        static void ForeachCheck(Product[] products)
        {
            foreach (var product in products) {
                if (!product.Price.HasValue) {
                    throw new Exception("Prease Enter a defalut price");
                }
            }
        }
        static decimal ForeachSum(Product[] products)
        {
            decimal sum = 0M;
            foreach (var product in products) {
                if (product.Price < 400M) {
                    sum += product.Price.Value;
                }
            }
            return sum;
        }
    }
    public class Product
    {
        public int ProductID { get; set; }

        public string Name { get; set; }

        public string Description { get; set; }

        public decimal? Price { get; set; }

        public string Category { get; set; }
    }

 

 Linq=>

    class Program
    {
        static void Main(string[] args)
        {
            var products = new Product[]{ 
                                        new Product(){Name="Kayak" , Price=9.5M},
                                        new Product(){Name="Lifejacket" , Price=48.95M},
                                        new Product(){Name="Scooceer ball" , Price=19.5M},
                                        new Product(){Name="Stadium" , Price=79550M}
                                    };
            Check(products);
            var sum1 = Sum(products);
            Console.WriteLine(sum1);
            Console.Read();
        }
        static void Check(Product[] products)
        {
            if(products.Any(p=>!p.Price.HasValue))
                throw new Exception("Prease Enter a defalut price");
        }
        static decimal Sum(Product[] products)
        {
            return products.Where(p => p.Price.Value < 400M).Sum(p => p.Price.Value); ;
        }
    }

 

相关文章:

  • 2022-12-23
  • 2022-12-23
  • 2021-07-11
  • 2022-12-23
  • 2022-01-16
  • 2021-09-06
  • 2021-08-25
  • 2022-12-23
猜你喜欢
  • 2021-11-26
  • 2022-12-23
  • 2022-02-02
  • 2022-12-23
  • 2022-12-23
  • 2021-12-29
  • 2022-12-23
相关资源
相似解决方案