Search code examples
c#listitems

how to clear list till some item? c#


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


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;
    }