Announcement

Collapse
No announcement yet.

Partner 728x90

Collapse

Adding the last x list entries

Collapse
X
 
  • Filter
  • Time
  • Show
Clear All
new posts

    Adding the last x list entries

    Hi. I wanna add the last X entries of my list together with X being a changeable property.

    the way i do it atm is to just use an if statement for every X i would like, so

    if(x==1)
    savedListvalue[savedListvalue.Count-1].Value

    if(x==2)
    savedListvalue[savedListvalue.Count-1].Value + savedListvalue[savedListvalue.Count-2].Value

    if(x==3)
    savedListvalue[savedListvalue.Count-1].Value + savedListvalue[savedListvalue.Count-2].Value + savedListvalue[savedListvalue.Count-3].Value


    and so on and so forth. needless to say that this is rather awkward and static and makes the code really blown up pretty fast

    anyone an idea for an more elegant way?

    #2
    Hello,

    Thank you for the question.

    It looks like you are just trying to Add the X number of items in the list together is this correct?

    Are you trying to on each iteration add only the next value or start with the Count-1 value, then add Count-2 to that, then Count-3 to that etc?

    If so you could use a simple loop, depending on what direction of the list you want to iterate you may need to adjust the code:

    Code:
    double accumulatedTotal = 0;
    for(int i = savedListvalue.Count - 1; i >  0; i--) 
    {
        accumulatedTotal += savedListvalue[i].Value;
    }


    This would start at the last index of the list and work its way back through the lists count, you could modify this to only do X items if you wanted too.

    the += would accumulate the value to the variable so if you are simply trying to add X numbers together, this would be an easy way to condense the code.

    I look forward to being of further assistance.

    Comment

    Latest Posts

    Collapse

    Topics Statistics Last Post
    Started by Geovanny Suaza, 02-11-2026, 06:32 PM
    0 responses
    571 views
    0 likes
    Last Post Geovanny Suaza  
    Started by Geovanny Suaza, 02-11-2026, 05:51 PM
    0 responses
    330 views
    1 like
    Last Post Geovanny Suaza  
    Started by Mindset, 02-09-2026, 11:44 AM
    0 responses
    101 views
    0 likes
    Last Post Mindset
    by Mindset
     
    Started by Geovanny Suaza, 02-02-2026, 12:30 PM
    0 responses
    548 views
    1 like
    Last Post Geovanny Suaza  
    Started by RFrosty, 01-28-2026, 06:49 PM
    0 responses
    548 views
    1 like
    Last Post RFrosty
    by RFrosty
     
    Working...
    X