Linq和foreach

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); ;
        }
    }

 

posted @ 2015-06-23 17:07  江境纣州  阅读(477)  评论(0编辑  收藏  举报