What about Linq?
Today, I suddenly wondered if I would continue to loop the remaining data when the conditions are met during the loop traversal of linq. I did a small experiment.
First look at the code
This is the test class.
Public class TestLinq {int _ Number; public int Number {get {Console. writeLine ("read Number" + _ Number); // here is to test whether the number value return _ Number has been read;} set {_ Number = value ;}}}
First, let's take a look at how to traverse the list directly using linq. The Code is as follows:
class Program { static void Main(string[] args) { List<TestLinq> lstTestLinq = new List<TestLinq>(); for (int i = 0; i < 10; i++) { lstTestLinq.Add(new TestLinq() { Number = i }); } var test = from c in lstTestLinq where c.Number < 8 select c; Console.ReadKey(); } }
The effect is as follows:
I didn't see any value of Console. WriteLine. It can be seen that if only the linq code is defined, but it is not used, this code will not be executed.
Continue to read the code:
class Program { static void Main(string[] args) { List<TestLinq> lstTestLinq = new List<TestLinq>(); for (int i = 0; i < 10; i++) { lstTestLinq.Add(new TestLinq() { Number = i }); } var test = from c in lstTestLinq where c.Number < 8 select c; test.ToList(); Console.ReadKey(); } }
:
We can see that linq reads all the data. After a ToList clause is added, linq is actually executed. If I change to ToArray, the effect is the same as that of ToList (). If I only want to retrieve one piece of data, so Will linq traverse all of them and continue to look at them.
class Program { static void Main(string[] args) { List<TestLinq> lstTestLinq = new List<TestLinq>(); for (int i = 0; i < 10; i++) { lstTestLinq.Add(new TestLinq() { Number = i }); } var test = from c in lstTestLinq where c.Number < 8 select c; test.First(); Console.ReadKey(); } }
The effect is as follows:
Next we will execute the First or FirstOrDefault Method for linq, so what about skip and take? Continue the test.
class Program { static void Main(string[] args) { List<TestLinq> lstTestLinq = new List<TestLinq>(); for (int i = 0; i < 10; i++) { lstTestLinq.Add(new TestLinq() { Number = i }); } var test = from c in lstTestLinq where c.Number < 8 select c; test.Skip(2).Take(1); Console.ReadKey(); } }
No execution was found
The following describes other methods, such as AsQueryable () and AsEnumerable ().
The same is true.
The first time a newbie blogs, he is well aware of the confusion of new recruits. Next, let's see if the EF operation database is really as bad as it is in the legend.
QQ Group for newcomers 165609857