扩展方法where方法查询不到数据,不会抛异常,也不是返回的null

如题,“扩展方法where方法查询不到数据,不会抛异常,也不是返回的null”,示例代码如下:

Product类:

 public class Product
    {
        private string name;

        public string Name
        {
            get { return name; }
            set { name = value; }
        }

        private double price;

        public double Price
        {
            get { return price; }
            set { price = value; }
        }

        public override string ToString()
        {
            return string.Format("{0}:{1}", Name, Price);
        }
    }
View Code

Main函数:

 static void Main(string[] args)
        {
            Console.WriteLine("验证where方法查询不到数据,不会抛异常,也不是返回的null。");
            Console.WriteLine();

            List<Product> list = new List<Product> 
            {
                new Product{Name="三文鱼",Price=205.5},
                new Product{Name="鲫鱼",Price=15.5},
                new Product{Name="秋刀鱼",Price=10},
                new Product{Name="猪肉",Price=18.5},
                new Product{Name="牛肉",Price=70.5},
                new Product{Name="驴肉",Price=100}
            };
            Console.WriteLine("------------FindAll方法(单价大于30的商品)-----------");
            list.FindAll(p => p.Price > 30).ForEach(Console.WriteLine);
            Console.WriteLine();

            Console.WriteLine("------------Where方法(单价大于30的商品)-----------");
            foreach (var item in list.Where(p=>p.Price>30))
            {
                Console.WriteLine(item);
            }
            Console.WriteLine();

            //验证where方法查询不到数据,不会抛异常,也不是返回的null
            Console.WriteLine("------------Where方法(单价大于30000的商品)---------");
            var num=list.Where(p => p.Price > 30000).Count();
            Console.WriteLine("有{0}个单价大于30000的商品。",num);
            Console.ReadKey();
        }
View Code

假如 list.Where(p => p.Price > 30000)  返回null,则list.Where(p => p.Price > 30000).Count()会抛异常。

事实上代码正确地运行了,即验证了:

扩展方法where方法查询不到数据,不会抛异常,也不是返回的null

运行截图如下:

原文地址:https://www.cnblogs.com/527289276qq/p/4444126.html