How to clear the list to a specific item? WITH#

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

if i use List.Clear(), all items are deleted.

I need to delete to a specific item, for example, to [1]. this means that there is only in my list 2 items [0] and [1]. how to do it with c #?

+5
source share
5 answers

You can use List.RemoveWhere (Predicate). Alternatively, you can do the for-looping loop backward, removing elements until you

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

If you want to delete all elements after index 1 (that is, save only the first two elements):

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

"[1]", :

int index = yourList.FindIndex(x => x == "[1]");
if (index >= 0)
    yourList.RemoveRange(index + 1, yourList.Count - index - 1);
+8

GetRange.

..

myList = myList.GetRange(0,2);

.. , .

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

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

0
source

You can remove a range from the list by specifying the starting index and the number of items to delete.

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

All Articles