Sean M
Sean M

Reputation: 23

Convert loop to LINQ

A list of Equity Analytics (stocks) objects doing a calculation for daily returns. Was thinking there must be a pairwise solution to do this:

for(int i = 0; i < sdata.Count; i++){
    sdata[i].DailyReturn = (i > 0) ? (sdata[i-1].AdjClose/sdata[i].AdjClose) - 1
                                   : 0.0;
}

Upvotes: 2

Views: 254

Answers (2)

gdoron
gdoron

Reputation: 150313

LINQ stands for: "Language-Integrated Query".

LINQ should not be used and almost can't be used for assignments, LINQ doesn't change the given IEnumerable parameter but creates a new one.

As suggest in a comment below, there is a way to create a new IEnumerable with LINQ, it will be slower, and a lot less readable.

Though LINQ is nice, an important thing is to know when not to use it.

Just use the good old for loop.

Upvotes: 2

Nikola Davidovic
Nikola Davidovic

Reputation: 8666

I'm new to LINQ, I started using it because of stackoverflow so I tried to play with your question, and I know this may attract downvotes but I tried and it does what you want in case there is at least one element in the list.

sdata[0].DailyReturn = 0.0;
sdata.GetRange(1, sdata.Count - 1).ForEach(c => c.DailyReturn = (sdata[sdata.IndexOf(c)-1].AdjClose / c.AdjClose) - 1);

But must say that avoiding for loops isn't the best practice. from my point of view, LINQ should be used where convenient and not everywhere. Good old loops are sometimes easier to maintain.

Upvotes: 0

Related Questions