Group repeating sql fill statement values from DropDownList

2

I'm getting information from a table and filling a DropDownList , but I have a lot of information repeated and would like to group the values so they do not repeat in DropDownList .

Example information I'm capturing.

Cidade1

Cidade2

Cidade1

Cidade1

Cidade3

I would like the DropDownList to only receive Cidade1 , Cidade2 and Cidade3 without repetition.

In Controller I am using the following statement, but I did not succeed:

List<Empresa> items = db.Empresa.OrderBy(x => x.Cidade).ThenBy(x => x.Cidade).ToList();
    
asked by anonymous 10.10.2017 / 20:33

3 answers

3

One way to avoid repeating values in a given field is to use the Distinct() method, see a reproducible example:

using System;
using System.Linq;
using System.Collections.Generic;

public class Program
{
    class Endereco
    {
        public string Cidade { get;set;}
    }

    public static void Main()
    {
        List<Endereco> enderecos = new List<Endereco>
        {
            new Endereco {Cidade = "Cidade1"},
            new Endereco {Cidade = "Cidade2"},
            new Endereco {Cidade = "Cidade3"},
            new Endereco {Cidade = "Cidade1"},
            new Endereco {Cidade = "Cidade4"},
        };

        var enderecosDistinct = enderecos.Select(x => x.Cidade).Distinct();

        enderecosDistinct.ToList().ForEach(c => Console.WriteLine(c));
    }
}

Output:

  

City1
  City2
  City3
  City4

See working at .NET Fiddle .

More information on this answer .

    
10.10.2017 / 20:55
2

I did it this way, which did not escape the tips provided in the forum @gato @Ronivaldo Roner

private ApplicationDbContext db = new ApplicationDbContext();

public ActionResult Index()
        {
            ViewBag.cidade= new SelectList(db.Empresa.Select(a => a.Cidade).Distinct());
            return View();
        }

@Html.DropDownList("cidade", null, htmlAttributes: new { @class = "form-control" })
    
11.10.2017 / 00:10
1

Try to use .Distinct() , I believe it will solve your problem.

    
10.10.2017 / 20:55