Group repeated values of Dropdownlist fill sql statement

Asked

Viewed 97 times

2

I’m taking information from a table and filling out a DropDownList, but I have a lot of information repeated and I would like to group the values so that they are not repeated in the DropDownList.

Example of information I’m capturing.

Cidade1

Cidade2

Cidade1

Cidade1

Cidade3

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

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

List<Empresa> items = db.Empresa.OrderBy(x => x.Cidade).ThenBy(x => x.Cidade).ToList();
  • It would be something like a distinct campo in consultation?

  • You see the problem is that in the Dropdownlist is coming repeated values, have you passed me the Distinct statement ? So the synthesis List<Company> items = db.Empresa.Orderby(x => x.City) is wrong. Distinct(x => x.City). Tolist();

  • If you want something more complete, it exists this library maintained by Jon Skeet :D There you will find an improved version of the method Distinct() which is the DistinctBy() it allows returning objects instead of single values.

3 answers

3


One way to avoid repeating values of a given field is to use the method Distinct(), 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));
    }
}

Exit:

City1
City2
City3
City4

See working on .NET Fiddle.

More information on this reply.

2

I did 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" })

1

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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.