Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove all occurrences of an item in ArrayList

Tags:

c#

arraylist

I am trying to remove all occurrences of an item in the arraylist

ArrayList list=new ArrayList();
list.Add("2.2");
list.Add("2.5");
list.Add("2.6");
list.Add("2.2");
list.Add("2.5");
list.Add("2.2");

How can remove all 2.2 values from the list?I have used

list.Remove("2.2")

but it removes only first occurrence

like image 790
shubhendu Avatar asked Sep 23 '14 09:09

shubhendu


People also ask

How do you remove multiple elements from an ArrayList in Java?

Core Java bootcamp program with Hands on practice The List provides removeAll() method to remove all elements of a list that are part of the collection provided.

How do you clear all elements in an array Java?

If the elements in the array are no longer desired and what you want is an empty array (i.e., an array with zero elements) ready to be used again then you can use myArray. clear(); or myArray = new ArrayList(); .


1 Answers

Read the docs on ArrayList.Remove(), in particular:

Removes the first occurrence of a specific object from the ArrayList.

Why are you using an ArrayList anyway? The elements in your example are all the same type, you would be better off using a List<string> and then using RemoveAll e.g.

List<string> list = new List<string>();
list.add("2.2");
list.add("2.5");
list.add("2.6");
list.add("2.2");
list.add("2.5");
list.add("2.2");

list.RemoveAll(item => item == "2.2");
like image 195
DGibbs Avatar answered Sep 22 '22 05:09

DGibbs