简体   繁体   English

在asp.net mvc 5的下拉列表中有区别

[英]Distinct in dropdown list in asp.net mvc 5

How to remove duplicate records from dropdown list this is working fine for me but I am getting records more than two because I have same names in my database but I want to remove duplicate records. 如何从下拉列表中删除重复记录,这对我来说很好,但由于数据库中具有相同的名称,但我想删除多个记录,所以我获得的记录超过两个。

public ActionResult Index()
{
    List<OrbatTable> CountryList = db.OrbatTables.ToList();
    ViewBag.CountryList = new SelectList(CountryList, "CityName", "CityName");
    return View();             
}

public JsonResult GetStateList(String CityName)
{
    db.Configuration.ProxyCreationEnabled = false;
    List<OrbatTable> StateList = db.OrbatTables.Where(x => x.CityName == CityName)
        .Distinct().ToList();
    return Json(StateList, JsonRequestBehavior.AllowGet);        
}

and this is my code for drop down list 这是我的下拉列表代码

@if (ViewBag.CountryList != null)
{
    @Html.DropDownListFor(model => model.CityName, ViewBag.CountryList as SelectList, 
        "--Select City", new { @class = "form-control" })            
}

GroupBy can used here. GroupBy可以在这里使用。

List<OrbatTable> StateList = db.OrbatTables.GroupBy(x => x.CityName == CityName)
        .Select(x =>x.First()).ToList();

2 options come to mind if I understand what your goal is: 如果我了解您的目标是,有两种选择:

(each option is a suggested edit to the body of your GetStateList method) (每个选项都是对GetStateList方法主体的建议编辑)

  1. To stick close to what you are currently doing, you could try a nifty DistinctBy approach 要紧贴您当前正在执行的操作,可以尝试一种巧妙的DistinctBy方法

  2. You could create an empty target list and then iterate over your source list adding each item to the target list only if it's not already in the target list 您可以创建一个空的目标列表,然后遍历您的源列表,仅当每个项目不在目标列表中时,才将其添加到目标列表中

(I would have just commented, but my reputation is not high enough.) (我刚才已经发表评论,但是我的声誉还不够高。)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM