Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove item from SelectList in C#

Tags:

c#

selectlist

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.

like image 893
impream Avatar asked Dec 02 '22 14:12

impream


2 Answers

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();
   }

}
like image 70
Ehsan Sajjad Avatar answered Dec 10 '22 13:12

Ehsan Sajjad


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();
}
like image 27
Mukesh Kalgude Avatar answered Dec 10 '22 13:12

Mukesh Kalgude