MHP
MHP

Reputation: 81

How to Refactor LINQ

How can I refactor this code?

Is it possibel to make the aktuelKurs og kursFagenFor in the same line?

EDIT 2

  if (aktiekurser != null)
  {
    int idDato = aktiekurser.Last().IdDato;

    for (int i = 0; i < antalDage; i++)
    {
      aktuelKurs = (from a in aktiekurser
                    where a.IdDato == idDato - i
                    select a.Lukkekurs
                    ).Sum();

      kursDagenFor = (from a in aktiekurser
                    where a.IdDato == idDato - (i + 1)
                    select a.Lukkekurs
                    ).Sum();

      gnsOp += aktuelKurs > kursDagenFor ? aktuelKurs :0m;
    }
  }

Upvotes: 0

Views: 92

Answers (1)

Gert Arnold
Gert Arnold

Reputation: 109079

This isn't very efficient. First, you query each individual sum separately and, second, in each iteration you calculate a sum that was also calculated in the previous iteration.

You can make this much more efficient by querying al required sums in one grouping query:

var aktuelKurs = from a in aktiekurser
                 where a.IdDato >= idDato - 1 + antalDage
                 group a by a.IdDato into grp
                 select grp.Sum(x => x.Lukkekurs);

Now you have a list of decimals of which you have to determine if elements are greater than their predecessors and Sum the results according to your rule:

var gnsOp = aktuelKurs.Zip(aktuelKurs.Skip(1), 
                 (prev,act) => act > prev ? act :0m).Sum()

Upvotes: 1

Related Questions