Question

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#?

Was it helpful?

Solution

You can use the List.RemoveWhere(Predicate).. Alternatively, you can do a for loop - looping backwards, removing items till the item you're after ie

for(var i = List.Count()-1; i>=0; i--) {
   var item = List[i];
   if (item != "itemThatYourLookingFor") {
      List.Remove(item);
      continue;
   }
   break;
}

OTHER TIPS

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.

List<string> strings = new List<string>{"a", "b", "c", "d", "e"};
List<string> firstTwoStrings = strings.Take(2).ToList();
// firstTwoStrings  contains {"a", "b"}

The Take(int count) method will leave you with count items.

You can remove a range from a list, giving the starting index and the number of items to remove.

var items = new List<string> {"0", "1", "2", "3", "4", "5"};
var index = items.IndexOf("1") + 1;

if (index >= 0)
{
    items.RemoveRange(index, items.Count - index);
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top