vb.net LINQ 选择与列表不同

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13548596/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-17 11:17:42  来源:igfitidea点击:

vb.net LINQ select Distinct to a List

c#.netvb.netlinqdatatable

提问by user1590636

I have a datatablewith a column that has some duplicate values, I want to add those values to a listboxbut without duplicates

我有一datatable列有一些重复值,我想将这些值添加到 alistbox但没有重复

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?

但它给了我重复的值,没有重复怎么办?

回答by Kundan Singh Chouhan

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.

我相信每行中还有更多的列是唯一的,这就是为什么 distinct 没有按预期返回结果的原因。相反,您应该首先选择列,然后对其应用不同的列。

So try this instead :

所以试试这个:

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

Hope this will help !!

希望这会有所帮助!!

回答by Mark

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

您可以将 IEqualityComparer 传递给不同的函数。看到这个答案Distinct() 与 lambda?

回答by Felix Bagur

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.

我有同样的问题。我发现匿名类型不同的作品。所以我首先做distinct,然后复制到一个列表中。

    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