c# - LINQ's deferred execution, but how? -
This should really be something simple but I'm going to ask it in some way, because I think others There will be conflict with it too. Instead of always using the usual LINQ query, why not always execute with the new variable-value?
Fixed zero main (string [] args) {Console.WriteLine ("Enter something:"); String input = console Readline (); // For example ABC 123 var points = input Where (four. ISDIG); // 123 while (no.) {Console.WriteLine ("Enter a string that does not have digits"); Input = console Readline (); // ABC console for example). Wrightite ("Bye"); Console.ReadLine (); }
In the commented sample it will enter the loop after input ABC123
digits. But if you enter something like ABC
to digit
still 123
, it will never leave.
So why does the LINQ query not evaluate the new input
but always the first?
I know that I can fix it with this extra line:
while (number any) {Console.WriteLine ("Enter a string that Not included in the score "); Input = console Readline (); Points = input Where (four .isidigt); // now works as expected}
or - more elegant - using the query directly in the loop:
while (input.Any (Char isdigit)) {// ...}
The difference is that you 'Again content is changing the value of the input
variable instead of that object which refers to the variable ... then still the digit
The original collection is referred to.
Compare this code with:
list & lt; Char & gt; Input = new list & lt; Char & gt; (Console. Readline ()); Var points = input Where (Four. ISIDID); // 123 while (no.) {Console.WriteLine ("Enter a string that does not have digits"); Input.Clear (); Input.AddRange (Console.ReadLine ()); }
At this time, we are amending the archive content which refers to input
- and as such < Code> Points is effectively a view on that collection, we look at the change.
Comments
Post a Comment