简体   繁体   中英

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

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

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM