LINQ and Homework
My daughter asked me to check her homework today. One of the math problems was:
A book has 352 pages. How many 4's were used to print all of the page numbers.
She got 35. She explained how she arrived at that number and while her logic was good, it sounded too low to me. I started thinking about it a little and then decided I could just write a few lines of C# code to figure out the answer.
As Visual Studio was starting up, I pictured the code in my head: initialize a counter to zero. Loop through an int from 1 to 352 and see if the ToString() contains a 4. If so, increase the counter. Just as I was about to start typing, I thought, "Oh wait – I could do all of this with LINQ!".
var answer = Enumerable.Range(1, 352).Count(p => p.ToString().Contains("4"));
How did we ever manage before LINQ? ;)