chobo2
chobo2

Reputation: 85765

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

Upvotes: 5

Views: 37059

Answers (3)

Donil
Donil

Reputation: 1

we can make mouse selection over the autocomplete div by adding this following code

into the jquery autocomplete function

here i have used the id name as Requiredid

 $("#Requiredid").autocomplete({focus:function(e,ui) {
      document.getElementById('Requiredid').value = ui.item.label;
      document.getElementById('hdnValue').value = ui.item.id;//If You need this value you //can add this line
}});

Upvotes: 0

Matt Hamilton
Matt Hamilton

Reputation: 204129

You could use the RemovalAll method:

myList.RemoveAll(i => i.Text == "two");

Obviously this will get rid of all the items whose "Text" property is "two", but since you're using it in a ComboBox I'm assuming you'll only have one item for each "Text" value.

Upvotes: 7

Marc Gravell
Marc Gravell

Reputation: 1062770

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...

Upvotes: 8

Related Questions