如何从列表集合中删除对象? [英] How to remove an object from a list collection?

查看:282
本文介绍了如何从列表集合中删除对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不得不改变自己的代码行.我以前有这样的东西

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

但是,在我的其中一个页面上,我有一个下拉列表,不需要字段"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");

现在我需要将列表更改为List<SelectListItem> myList = new List<SelectListItem>();

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"},
            };

那么,现在如何删除包含两个"的selectListItem?我知道我可能可以使用按索引删除.但是我将来可能会添加到列表中,所以如果索引发生更改,我不想开始寻找并更改它.

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.

谢谢

推荐答案

List<T>将用于比较对象引用(除非SelectListItem实现自定义的相等方法).因此,除非您仍然对第二个项目有参考,否则您将不得不通过参考或查找所需项目

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

这篇关于如何从列表集合中删除对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆