c# – DropdownList with MVC unique values


My Galeria class has a foreign key with Album because there is a 1-n relationship and each photo in the Galeria item has an Album respectively. Given that, in the CMS I created I give the user the possibility to relate a photo to an Album at the time of upload. For that, my View looks like this:

<div class="editor-label">
   Cursos @Html.DropDownList("Album", ViewData["Cursos"] as SelectList)

And my Controller:

AlbumAplicacao bdAlbum;
   bdAlbum = AlbumAplicacaoConstrutor.AlbumAplicacaoEF();
   var list = new SelectList(bdAlbum.ListarTodos().OrderByDescending(x => x.Nome), "ID", "Nome");
   ViewData["Cursos"] = list;

My Domain:

public class CONGRESSO_Galeria
    public int ID { get; set; }

    public string Descricao { get; set; }

    public string Foto { get; set; }

    public virtual CONGRESSO_Album CONGRESSO_Album { get; set; }


My problem is that I'm getting several identical values ​​in the Dropdown. I tried using Trim() and filtering using Distinct() but without success.

I noticed that the problem was generated because at the time of recording the item, I am recording an Album again. I'll fix this, but hundreds of items have already been registered and thanks to that, I need to find a way to change the display.



Try this:

     var list = new SelectList(bdAlbum.ListarTodos().OrderByDescending(x => x.Nome).GroupBy(x => x.Nome.ToLower().Trim()).Select(y => y.First()) , "ID", "Nome");

This way you will group all the same values.

The correct thing is to avoid that duplicate values ​​are inserted in your bank.

Scroll to Top