1
@foreach (var item in Model) { string mytown = item.town.*enter distinct here* <option value="@mytown"> @mytown</option> 

This selects all the town names in my database and I've got it to display in a drop down menu.

How can I change this so that when it's displaying the town names, it will only show each town name once.

For example, if I have 3 londons in the database it will show all 3 londons in the drop down menu. I want it to only show 1 london

FYI: Sorry this may seem like a repost but I posted the wrong code earlier

3
  • Its a repost.. but it doesn't change the answer from your previous question. Use Distinct. Commented Dec 12, 2013 at 4:28
  • You should do that in the controller. Commented Dec 12, 2013 at 4:28
  • @SimonWhitehead My apologies Commented Dec 12, 2013 at 4:30

3 Answers 3

2
myCollection.Select(x => x.Name).Distinct().ToList();
Sign up to request clarification or add additional context in comments.

Comments

1

As far as my understanding, you can't do this if you are using ID as value.

Say

ID | Value
1    Landon
2    Landon
3    Landon
4    Los Angeles

Better way you can achieve this is by using LINQ. Get the list from the database then filter it in the controller towns.Where(x => x.Name == x.Name.Distinct());

further Inside controller action

ViewBag.towns = new SelectList(towns.Where(x => x.Name == x.Name.Distinct()).ToList(), "Value", "Text");

Inside view

 @Html.DropDownListFor(x => x.SelectedTown, new SelectList(ViewBag.towns, "ID", "Name", Model.SelectedTown))

Comments

0

Why not convert it to a HashSet<string>()?

var hs = new HashSet<string>(Model);

given, Model is IEnumerable<string> ?

Or, do that in the controller, by converting the List<T> to HashSet<T> and then pass it as an IEnumerable<T> to the model.

or this one:

from y in Model.Distinct() select y

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.