Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove an object from a list collection?

I had to change on my lines of code around. I before had something like this

// this is in a static method.
List<string> mySTring = new List<string>();

mySTring.add("one");
mySTring.add("two");

However on one of my pages I have a dropdownlist that does not require the field "two" so instead of writing duplicate code all I did was

myString.remove("two");

Now I need to change my list to a List<SelectListItem> myList = new List<SelectListItem>();

So I have it now looking like this:

  List<SelectListItem> myList = new List<SelectListItem>()
            { 
                new SelectListItem() { Text = "one", Value = "one"},
                new SelectListItem() { Text = "two", Value = "two"},
            };

So now how do I remove the selectListItem that contains "two"? I know I probably could use remove by index. But I might add to list in the future so I don't want to start hunting down and changing it if the index changes.

Thanks

like image 264
chobo2 Avatar asked Nov 08 '09 22:11

chobo2


People also ask

How do I remove an object from a list in Python?

In Python, use list methods clear() , pop() , and remove() to remove items (elements) from a list. It is also possible to delete items using del statement by specifying a position or range with an index or slice.

How do I remove an object from a list in Java?

There are two ways to remove objects from ArrayList in Java, first, by using the remove() method, and second by using Iterator. ArrayList provides overloaded remove() method, one accepts the index of the object to be removed i.e. remove(int index), and the other accept objects to be removed, i.e. remove(Object obj).

Can we remove an object from ArrayList?

There are 3 ways to remove an element from ArrayList as listed which later on will be revealed as follows: Using remove() method by indexes(default) Using remove() method by values. Using remove() method over iterators.

Which function is used for removing object from list?

Python list remove() Python List remove() is an inbuilt function in the Python programming language that removes a given object from the List. Parameters: obj: object to be removed from the list.


1 Answers

List<T> is, by default, going to be comparing object references (unless SelectListItem implements a custom equality method). So unless you still have a reference to the second item around, you are going to have to get it either by reference, or by finding the desired item:

var item = myList.First(x=>x.Value == "two");
myList.Remove(item);

Index may be easier...

like image 108
Marc Gravell Avatar answered Sep 28 '22 16:09

Marc Gravell