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#?
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.
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.
To empty a C# list, use the Clear() method.
To remove an item from a list in C# using index, use the RemoveAt() method.
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);
You can use the GetRange method.
So..
myList = myList.GetRange(0,2);
..would give you what you are asking for above.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With