Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to clear list till some item? c#

Tags:

c#

list

items

i have List<sting> with 5 entries. [0],[1],[2],[3],[4].

if I use List.Clear() all item are removed.

i need remove till specific item, for example till [1]. that means in my list are just 2 items [0] and [1]. how do that with c#?

like image 726
r.r Avatar asked Jun 16 '11 13:06

r.r


People also ask

How do I remove all items from a list?

There are three ways in which you can Remove elements from List: Using the remove() method. Using the list object's pop() method. Using the del operator.

How do I remove all items from list controls?

Use the RemoveAt or Clear method of the Items property. The RemoveAt method removes a single item; the Clear method removes all items from the list.

How do you clear a list in C sharp?

To empty a C# list, use the Clear() method.

How do I remove one item from a list in C#?

To remove an item from a list in C# using index, use the RemoveAt() method.


2 Answers

If want to remove all items after index 1 (that is, retain only the first two items):

if (yourList.Count > 2)
    yourList.RemoveRange(2, yourList.Count - 2);

If you need to remove all items after the item with a value of "[1]", regardless of its index:

int index = yourList.FindIndex(x => x == "[1]");
if (index >= 0)
    yourList.RemoveRange(index + 1, yourList.Count - index - 1);
like image 143
LukeH Avatar answered Sep 23 '22 09:09

LukeH


You can use the GetRange method.

So..

myList = myList.GetRange(0,2);

..would give you what you are asking for above.

like image 35
heisenberg Avatar answered Sep 24 '22 09:09

heisenberg