[英]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 但是在我的一个页面上,我有一个不需要字段“2”的下拉列表,所以我所做的只是编写重复的代码而不是
myString.remove("two");
Now I need to change my list to a List<SelectListItem> myList = new List<SelectListItem>();
现在我需要将列表更改为
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"? 那么现在如何删除包含“two”的selectListItem? 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). 默认情况下,
List<T>
将比较对象引用(除非SelectListItem
实现自定义相等方法)。 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: 您可以使用RemovalAll方法:
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. 显然,这将删除所有 “Text”属性为“two”的项目,但由于你在ComboBox中使用它,我假设你每个“Text”值只有一个项目。
we can make mouse selection over the autocomplete div by adding this following code 我们可以通过添加以下代码在autocomplete div上进行鼠标选择
into the jquery autocomplete function 进入jquery自动完成功能
here i have used the id name as Requiredid 这里我使用了id名称作为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
}});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.