Remove item from SelectList in C#

13.4k views Asked by At

I have a method in which return me selectList. The certain items of selectList are to be programatically removed on the basis of 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;
    }

For eaxmple , I have to remove the item with Key "Disapprove". Could any one kindly help me to solve this.

3

There are 3 answers

2
Ehsan Sajjad On BEST ANSWER

You have to use Where() to filter them and then pass returned object of List<SelectListItem> to SelectList constructor to get the new SelectList which will not have item with Value "Disapprove" this way:

public class SomeController
{

   public ActionResult Index()
   {

       SelectList list = GetRoutingActionList();

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

        return View();
   }

}
0
Mukesh Kalgude On
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();
}
0
Yogi On

Simply remove it from dictionary. Being a reference it will automatically removed from the SelectList.

routingActions.Remove("Disapprove");