r.r
r.r

Reputation: 7153

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

Upvotes: 5

Views: 5767

Answers (5)

Peter Kelly
Peter Kelly

Reputation: 14391

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

Upvotes: 0

LukeH
LukeH

Reputation: 269368

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

Upvotes: 8

Matt Ellen
Matt Ellen

Reputation: 11592

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.

Upvotes: 0

Jason Jong
Jason Jong

Reputation: 4330

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

Upvotes: 2

heisenberg
heisenberg

Reputation: 9759

You can use the GetRange method.

So..

myList = myList.GetRange(0,2);

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

Upvotes: 4

Related Questions