Sorin Pascu
Sorin Pascu

Reputation: 29

Max out of a range of List values

I am trying to find the Max value out of the last five HSwDMI List values, but I am not sure if my for() loop is the right way of doing it. I would have thought that I could use a function to give me the highest value in the last five, but I couldn't find anything.

Also, the code below throws the error "Use of unassigned local variable newHSwDMI" and I can't quite get why. It works when I declare newHSwDMI at class level, though.

Any advice will be appreciated.

private List<double> HSwDMI;
HSwDMI = new List<double>();
....
if ((!HSwDMIbool && DMI1[2] - DMI1[1] > 0.001 && DMI1[2] - DMI1[3] > 0.001)
    || (!HSwDMIbool && FlatIndBar && FlatDMI[a-1] - DMI1[1] > 0.001 && FlatDMI[a-1] - DMI(Closes[2], 
    Convert.ToInt32(DmiPeriod)).Values[0].GetValueAt(flatDMIbar - 1) > 0.001))
{
    var hSwDMI = DMI1[2];
    HSwDMI.Add(hSwDMI);
    HSwDMIbar = CurrentBar - 2;
    var hSwDMIprice = Highs[2].GetValueAt(HSwDMIbar);
    HSwDMIprice.Add(hSwDMIprice);
    HSwDMIbool = true;
    b++;
}
if (HSwDMIbool)   
{
    double newHSwDMI;
    for ( int i = 1; i <= 5; i++)
    {
        if (HSwDMI[i] > HSwDMI[i-1])
            newHSwDMI = HSwDMI[i];
    }
    LastHSwDMI.Add(newHSwDMI);
}

Upvotes: 1

Views: 470

Answers (1)

Asım G&#252;nd&#252;z
Asım G&#252;nd&#252;z

Reputation: 1297

by using linq you could do something like this

var listCount = HSwDMI.Count; 
var maxValueInHswDMI = HSwDMI.Skip(listCount-5).Max();

// HSWDMI.Skip(x) skips x amount of items in the list and max returns the max value among the remaining items..

Hope this helps!

Upvotes: 2

Related Questions