0

I have a logging table that lists all of the updates our customers receives. In the column, the company code can be listed several times. I need to get a list of all available codes in the list but only show them once.

Here is my column:

enter image description here

I'd like to query the column and only return:

DEM
FRK

And not:

DEM
DEM
DEM
FRK

I can query the list as such:

private void PopulateCompanyCodes()
{
  var entity = new SuburbanWebServiceEntities();
  var qry = from x in entity.UpdateLogs
            select x.CompanyCode;

  comboBox_CompanyCodes.Items.Add(string.Empty);
  foreach (var cc in qry.ToList())
  {
    comboBox_CompanyCodes.Items.Add(cc);
  }
  comboBox_CompanyCodes.Text = string.Empty;
}

But of course, I'm getting DEM listed several times:

enter image description here

Is there a way to get the first list, only showing each item once for a combobox?

Thank you!

ErocM
  • 4,505
  • 24
  • 94
  • 161

3 Answers3

3

Use Distinct. You'll have to switch to method syntax but that's no big deal.

var qry = entity.UpdateLogs.Select(l => l.CompanyCode).Distinct();

comboBox_CompanyCodes.Items.Add(string.Empty);
foreach (var cc in qry.ToList())
{
    comboBox_CompanyCodes.Items.Add(cc);
}
Dave Zych
  • 21,581
  • 7
  • 51
  • 66
1

have you tried doing it like this. Using Distinct gets rid of duplicates.

foreach (var cc in qry.Distinct().ToList())
KratosMafia
  • 333
  • 1
  • 16
0

Use group by:

var qry = entity.UpdateLogs.GroupBy(l => l.CompanyCode);
Galma88
  • 2,398
  • 6
  • 29
  • 50