Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Remove from a list from starting index at once

I would like to remove elements from a list at once. Not in a loop.
Currently I am passing a from index number as a starting number and then removing it in a loop which is causing a lot of problems. Is there a way to remove all at once?

Basically remove from index 3 till the end.

public List<string> steps = new List<string> (); //Total count 10
public int fromIndex; //index is 3

void Start(){

        int tempTrackNumber =  fromIndex;
        
        for(int i = tempTrackNumber; i < steps.Count; tempTrackNumber++) {
            steps.Remove(steps[i]);
        }

}

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

If the goal is to remove elements from index X to the end of the list then the goal is also to keep only the first X-1 elements, which can be done with .Take():

steps = steps.Take(fromIndex - 1).ToList();

Semantically you can then clarify the meaning of fromIndex to something like keepCount:

steps = steps.Take(keepCount).ToList();

(Adjusting for the off-by-one calculation when setting that value, of course.)

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading