Refactoring to C# LINQ (C-Sharp, English): Get Stock Quote Data and Historical Stock Prices

Uploaded by TuomasHietanen on 16.01.2011

In this video I show how to refactor an old program to better new form.
The progam get stock quotes from the Yahoo Finance.
C# has changed a lot in few years to be more of a (multiparadigm/) functional language.
The legacy code here is quite good, it doesn't have class variables or other dependencies.
First I copy the old code to a new file...
I add a reference to the LINQ-library
I won't focus on the first two methods right now...
The first change is to make use of IEnumerable in the lists. It is the base class of lists.
IEnumerable can be lazy, so the execution (/enumeration) won't done until you really need the result.
LINQ is based on not modifying the IEnumerable but returning a new set
whom is the result of execution of a list operation 0:01:10.000,0:01:14.000 LINQ is declarative.We are focused of what the computer does, not how it does it.
Now, notice the similarity
Next a condition, or should I say "filter"
Usually when there are inner loops you would write an SelectMany
In this case we can do this even easier
Then just throw the legacy code away
We don't want to modify the list. It would be also better not to use the direct indexes.
We are not interested of objects to be removed but the remaining set
The next function seems to be a transform from type to another, or should I say "mapping".
Mapping is the "select" in LINQ.
The method returns a Tuple, which contains some different types of variables
Another evaluation-time-execution way would be using the yield return syntax.
Which goes like this...
This has only the problem that we still tell the computer how to do, not what to do.
I guess in unit tests this would be useful
Something should be done to the parsing. Maybe separate functions.
These can be made easily with the lambda-syntax...
string in, DateTime out
And then the same to decimal
Hmm... There is a bug, but I won't debug it now...
I just rename the old methods
Seems like this first gets the max value and then returns the corresponding item
Linq can be divided to queries and aggregates. Max is an aggregate.
It is just a shortcut to the Aggregate function of the LINQ
which takes in the accumulation-function. In this case, "select bigger".
These are exactly the same, use which one you like...
A fourth of the program got removed
Ohh, the class still has its old name, this explains the bug.