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" })            
}
2
  • its not working Commented Apr 30, 2018 at 10:42
  • thanks i have done by using this code in my Public ActionResult Index(){ List<OrbatTable> CountryList = db.OrbatTables.DistinctBy(x => x.CityName).ToList(); } Commented Apr 30, 2018 at 11:03

2 Answers 2

1

GroupBy can used here.

List<OrbatTable> StateList = db.OrbatTables.GroupBy(x => x.CityName == CityName)
        .Select(x =>x.First()).ToList();
Sign up to request clarification or add additional context in comments.

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.