MVC dropdownist绑定list之后除去list中的重复项

来源:互联网 发布:手机淘宝购物 编辑:程序博客网 时间:2024/06/06 03:44

在dropdownlist绑定数据库的时候,经常会有一些重复项需要删除,结合之前做二阶联动时的案例对程式做了一下修改:

model:

性别:@Html.DropDownList("SEX", @ViewData["SEX"] as IEnumerable<SelectListItem>,"--Please Choose--")性别_不重复:  @Html.DropDownList("SEX_SEL", @ViewData["SEX_SEL"] as IEnumerable<SelectListItem>, "--Please Choose--")


contoller:

    public ActionResult Index()        {                      List<namelist> llNameList = buildNameList();   //模拟数据源         ViewData["SEX"]=llNameList.Select(i=>new SelectListItem{Value=i.sex,Text=i.sex});            //增加code         Dictionary<string, int> dic = new Dictionary<string, int>();         int index = 1;         for (int _count = 0; _count < llNameList.Count; _count++)         {             if (!dic.ContainsKey(llNameList[_count].sex))             {                 dic.Add(llNameList[_count].sex, index++);             }         }         ViewData["SEX_SEL"] = dic.ToList().Select(i => new SelectListItem { Value = i.Key.ToString(),Text=i.Key.ToString()});            return View();        }

效果截图:


这里主要用到了dictionary和containskey结合,检索之后再查询制定键,关于dictionary说明,可参见https://msdn.microsoft.com/zh-cn/library/xfhwa508(VS.80).aspx,containskey可参见https://msdn.microsoft.com/zh-cn/library/system.collections.hashtable.containskey(v=VS.80).aspx



原创粉丝点击