0

I am trying to select the distinct rows from the database using the code given below. When i run this query it does not return the result what i am expected. I need distinct city names into dropdown control.

using (var context = new CountryEntities())
        {
            var city = (from u in context.Cities
                        where u.StateId == StateID
                        select new
                        {
                            cityId = u.CityId,
                            cityName = u.CityName

                        }).Distinct();


            cboCity.DataSource = city.ToList();
            cboCity.DataValueField = "CityId";
            cboCity.DataTextField = "CityName";
            cboCity.DataBind();
            cboCity.Items.Insert(0, new ListItem("--Select--", "0"));
        }

My database table is

enter image description here

What should i do. Please help me. Thanks in advance.

Jaan
  • 3,323
  • 7
  • 20
  • 24

1 Answers1

2

If you must ensure that there are no duplicate city names, you can do it like this:

var city = context.Cities
    .Where(u => u.StateId == StateID)
    .GroupBy(u => u.CityName)
    .Select(g => new {
        cityId = g.First().CityId,
        cityName = g.Key
    });

However, this has the consequence of throwing away some cities with duplicate names, because only one cityId is going to get used.

If you wish to overcome this limitation, you would need to introduce another column for disambiguation of the city - say, a area name or a postal code. Then you would need to change the code to append this disambiguation marker to names of cities that cannot be uniquely identified by their name alone.

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523