0

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" })            
}
Rufus L
  • 36,127
  • 5
  • 30
  • 43

2 Answers2

1

GroupBy can used here.

List<OrbatTable> StateList = db.OrbatTables.GroupBy(x => x.CityName == CityName)
        .Select(x =>x.First()).ToList();
Nagashree Hs
  • 843
  • 6
  • 18
0

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)

  1. To stick close to what you are currently doing, you could try a nifty DistinctBy approach

  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.)

egnomerator
  • 985
  • 8
  • 15