本文介绍了如何在SelectListItem中删除项目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从selectlistitem中删除一个项目。
到目前为止,我还没有获得成功

I am trying to remove an item from selectlistitem.so far, I have not gotten any success

这是代码的快照

使用System.Collections.Generic;

using System.Collections.Generic;

        List<SelectListItem> abcd = new List<SelectListItem>();
        SelectListItem i1 = null;
        i1 = new SelectListItem();
        i1.Text = "t0";
        i1.Value = "v0";
        i1.Selected = false;
        abcd.Add(i1);
        i1 = new SelectListItem();
        i1.Text = "";
        i1.Value = "";
        i1.Selected = false;
        abcd.Add(i1);
        i1 = new SelectListItem();
        i1.Text = "t1";
        i1.Value = "v1";
        i1.Selected = false;
        abcd.Add(i1);

我尝试删除与以下项匹配的abcd项之一:

I've tried to remove one of the abcd item that matches with:

        SelectListItem f = new SelectListItem();
        f.Selected = false;
        f.Text = "t0";
        f.Value = "v0";
        f.Selected = false;

        int x = abcd.IndexOf(f);  //return -1
        bool b = abcd.Remove(f); //return false

...,但未删除。
我试图找到索引,它总是返回-1
因为我不知道特定列表的位置,所以removeat方法将无济于事。

... but it did not remove.I tried to find the index, and it always return -1Since I don't know the position of a particular list, removeat method will not help.

非常感谢您的帮助

推荐答案

如果我正确理解您的想法,那应该可以。您将需要对此进行修改,以处理存在多个具有要删除的值的SelectListItem值,或者如果没有SelectListItem具有您的值的情况。

If I understand you correctly this should work. You will want to modify this to handle situations where there are multiple SelectListItem values with the value you want to remove, or if no SelectListItem has your value.

abcd.Remove(abcd.Where(c => c.Value == "v0").Single());

abcd = abcd.Where(c => c.Value != "v0").ToList();

abcd.RemoveAll(c => c.Value == "v0");

这篇关于如何在SelectListItem中删除项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-30 14:49