Linq 查询以列出 VB.NET

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7286097/
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-03 15:52:33  来源:igfitidea点击:

Linq query to list VB.NET

.netvb.netlinq

提问by serhio

Dim query = From o In myContainer.MyObjects Select o.MyStringProperty Distinct

Dim myProperties As List(Of String) = query.ToList????? 'no way!!!'

"query" type is IEnumerable(Of String)

“查询”类型是 IEnumerable(Of String)

I tried to use the querydirectly as a DataSource of a (infragistic) combobox, but it throws me NullReferenceException, so I decided to convert it to a listof strings, to be a more "classical" datasource.

我尝试将query直接用作(infragistic)组合框的数据源,但它向我抛出 NullReferenceException,因此我决定将其转换为字符串列表,以成为更“经典”的数据源。

Dim values As List(Of String) = query.AsQueryable().ToList()

does not work either: Value of type 'System.Collections.Generic.List(Of System.Linq.IQueryable(Of String))' cannot be converted to 'System.Collections.Generic.List(Of String)'.

也不起作用:“System.Collections.Generic.List(Of System.Linq.IQueryable(Of String))”类型的值不能转换为“System.Collections.Generic.List(Of String)”。

采纳答案by serhio

Finally, solved with good old method : )

最后,用很好的旧方法解决了:)

  Dim values As New List(Of String)

  For Each item In query
    values.Add(item)
  Next item

回答by Reed Copsey

Your error message suggests the queryis actually a List(Of T)containing a collection internally.

您的错误消息表明query它实际上是一个List(Of T)包含内部集合的集合。

If this is the case, you can use SelectManyto flatten the collection:

如果是这种情况,您可以使用SelectMany扁平化集合:

Dim values As List(Of String) = query.SelectMany(Function(m) m).ToList()


Edit: Given your edit, as well as the comment, the following should work fine:

编辑:鉴于您的编辑以及评论,以下内容应该可以正常工作:

Dim values As List(Of String) = query.ToList()

回答by avanek

Perhaps you should try to specify the type on the query variable?

也许您应该尝试在查询变量上指定类型?

Dim query = From o In myContainer.MyObjects Select o.MyStringProperty Distinct

Should become

应该成为

Dim query As IEnumerable(Of String) = From o In myContainer.MyObjects Select o.MyStringProperty Distinct

If the type of IEnumerable(Of String) can't be used on query, then you need to flatten the list as Reed Copsey said.

如果 IEnumerable(Of String) 的类型不能用于查询,那么您需要像 Reed Copsey 所说的那样展平列表。