从 C# 中的 SelectList 中删除项目

Remove item from SelectList in C#

我有一个方法 return 我选择列表。 selectList 的某些项目将在 Key 的基础上以编程方式删除。

 public SelectList GetRoutingActionList()
    {
        Dictionary<string, string> routingActions = new Dictionary<string, string> { 
                                                        { "Approved", "Approve" },
                                                        { "Return To", "Return To .." }, 
                                                        { "Return To Sender", "Return To Sender" }, 
                                                        { "Disapprove", "Disapprove" },
                                                        { "Set On Hold", "Set On Hold" } 
                                                    };

        SelectList routingActionList = new SelectList(routingActions, "Key", "Value");
        return routingActionList;
    }

对于 eaxmple ,我必须删除带有密钥 "Disapprove" 的项目。 谁能帮我解决这个问题。

你必须使用 Where() 来过滤它们,然后将 List<SelectListItem> 的返回对象传递给 SelectList 构造函数以获得新的 SelectList,它不会包含值为 [=16 的项目=]"Disapprove"这样:

public class SomeController
{

   public ActionResult Index()
   {

       SelectList list = GetRoutingActionList();

       list  = new SelectList(list 
                              .Where(x => x.Value != "Disapprove")
                              .ToList(),
                              "Value",
                              "Text");

        return View();
   }

}
public SelectList GetRoutingActionList()
    {
        Dictionary<string, string> routingActions = new Dictionary<string, string> { 
                                                        { "Approved", "Approve" },
                                                        { "Return To", "Return To .." }, 
                                                        { "Return To Sender", "Return To Sender" }, 
                                                        { "Disapprove", "Disapprove" },
                                                        { "Set On Hold", "Set On Hold" } 
                                                    };

        SelectList routingActionList = new SelectList(routingActions, "Key", "Value");
        return routingActionList.Where(x => x.Key != "Disapprove")
                                   .ToList();
}

只需将其从字典中删除即可。作为参考,它将自动从 SelectList 中删除。

routingActions.Remove("Disapprove");