1

I have a datatable with a column that has some duplicate values, I want to add those values to a listbox but without duplicates

I tried the following

Dim a = From row In table.AsEnumerable.Distinct.ToList Select row.Field(Of String)("name")

but it gives me duplicate values, How can it be done without duplicates?

BClaydon
  • 1,900
  • 2
  • 20
  • 34
user1590636
  • 1,174
  • 6
  • 26
  • 56

3 Answers3

9

I believe there are some more column(s) which are unique in each row that's why the distinct doesn't return the result as expected. Instead you should need to select the columns first than apply the distinct to it.

So try this instead :

Dim a = (From row In table.AsEnumerable()
        Select row.Field(Of String)("name")).Distinct().ToList()

Hope this will help !!

Kundan Singh Chouhan
  • 13,952
  • 4
  • 27
  • 32
  • 1
    To further comment, the reason his original query didn't work is because it was taking distinct rows - your example takes distinct based on the name field. – armen.shimoon Nov 25 '12 at 05:35
1

You can pass an IEqualityComparer to the distinct function. See this answer Distinct() with lambda?

Community
  • 1
  • 1
Mark
  • 1,718
  • 11
  • 10
0

I had the same problem. I found that on anonymous type distinct works. So I first do the distinct and then copy into a list.

    Dim  _ret = New List(Of Marcas)()
    For Each m In lista.Select(Function(s) New With {Key .id = s.BrandNo, .nombre = s.BrandName}).Distinct()
        _ret.Add(New Marcas With {.id = m.id, .nombre = m.nombre})
    Next