简体   繁体   English

vb.net LINQ选择与列表不同

[英]vb.net LINQ select Distinct to a List

I have a datatable with a column that has some duplicate values, I want to add those values to a listbox but without duplicates 我有一个datatable以具有一些重复值的列,我希望将这些值添加到listbox ,但没有重复

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? 但是它给了我重复的值,没有重复该怎么办?

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 !! 希望这会有所帮助!

You can pass an IEqualityComparer to the distinct function. 您可以将IEqualityComparer传递给不同的函数。 See this answer Distinct() with lambda? 查看此答案与lambda的Distinct()吗?

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM