linq延迟

一:linq延迟测试

对于linq的执行,在查询的时候是不会进行数据查询的,这样就会导致一些异常的出现,编译器可以编译通过,但是执行遍历的时候,就会出错,

当代码简短的时候程序员还可以找到问题,但是当程序经过好几次的调用的时候,在查询的时候出现异常,但是这个问题往往出现在linq查询哪里

这是由于linq的查询是有延迟的,在遍历的时候才会进行数据查询

具体错误重现

    private static void linqToSelect延迟()
        {
            string[] strings = { "one", "two", null, "three" };
            Console.WriteLine("aaa");
            IEnumerable<string> iestrings = strings.Where(s => s.Length == 3);
            Console.WriteLine("bbb");
            foreach (string s in iestrings)
            {
                Console.WriteLine(s);
            }
            Console.ReadKey();
        }

出现下面的异常,运行结果是aaa、bbb、one、two 出现此异常是由于代码在便利的时候,查询方法已经通过,但是在遍历的时候才真正的去查询数据,当查到第三个数据null的时候才出错,从运行结果可以看出这段代码已经执行到了foreach这里

注:当利用linq进行数据修改的时候

二:linq延迟说明  现在查询数组里面长度等于三的元素,从从代码可以看出,只进行了一次查询,运行结果为:one、two、111         aaa、two、111运行结果发生了变化,说明当代码执行的时候,在遍历元素的时候才进行数据查询

   private static void linqToSelect延迟()
        {
            string[] strings = { "one", "two", "111", "three" };
         
            IEnumerable<string> iestrings = strings.Where(s => s.Length == 3);
            
            foreach (string s in iestrings)
            {
                Console.WriteLine(s);
            }
            strings[0] = "aaa";
            foreach (string s in iestrings)
            {
                Console.WriteLine(s);
            }

            Console.ReadKey();
        }

 三:解决延迟,立即执行查询并缓存结果,

    private static void linqToSelect延迟()
        {
            string[] strings = { "one", "two", "111", "three" };
         
            //将查询结果缓存起来
            List<string> iestrings = strings.Where(s => s.Length == 3).ToList();
            //显示结果
            foreach (string s in iestrings)
            {
                Console.WriteLine(s);
            }
            //更改数据源
            strings[0] = "aaa";
            foreach (string s in iestrings)
            {
                Console.WriteLine(s);
            }

            Console.ReadKey();
        }

可以看出运行结果为one、two、111      one、two、111

原文地址:https://www.cnblogs.com/happygx/p/2451668.html