首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >尝试通过查询datacontext返回键/值对时,无法强制转换对象错误

尝试通过查询datacontext返回键/值对时,无法强制转换对象错误
EN

Stack Overflow用户
提问于 2019-04-22 21:22:32
回答 2查看 46关注 0票数 -5

我正在尝试从datacontext获取数据。通常,我没有遇到任何问题,但是我在尝试返回键/值对列表时遇到了问题。

基本上,我尝试从表中获取所有唯一的名称作为键列,以及它们在表中出现的次数作为值列。

我的数据将如下所示:

代码语言:javascript
复制
apple 5
banana 1
dragonfruit 3
.
.
.

完整的错误消息是:

无法将'System.Data.Linq.DataQuery1[VB$AnonymousType_32System.String,System.Int32]‘类型的对象强制转换为'System.Collections.Generic.List`1’类型

我使用的代码是这样的:

代码语言:javascript
复制
Dim indicators As List(Of Object)

Public Sub GetIndicatorData()
    Using context = new A_DataContext
    indicators = (From p In chartdata Group p By __groupByKey1__ = p.INDK8R Into g = Group
                      Select New With {.name = __groupByKey1__, .count = g.Count()}).AsEnumerable()
    indDataSource = indicators
End Sub

但我也尝试过:

  1. Return indicators as a list
  2. Return indicators as a enumerable。
EN

回答 2

Stack Overflow用户

发布于 2019-04-23 03:32:15

使用类来封装您的匿名类型

代码语言:javascript
复制
Public Class NameAndCount
    Public ReadOnly Property Name As String
    Public ReadOnly Property Count as Integer
    Public Sub New(name As String, count As Integer)
        Me.Name = name
        Me.Count = count
    End Sub
End Class

' ...

Private indicators As IEnumerable(Of NameAndCount)

Public Sub GetIndicatorData()
    Using context = new A_DataContext
        indicators = From p In chartdata Group p By __groupByKey1__ = p.INDK8R Into g = Group
                     Select New NameAndCount(__groupByKey1__, g.Count())
        indDataSource = indicators.ToList()
    End Using
End Sub
票数 0
EN

Stack Overflow用户

发布于 2019-04-22 21:33:06

我想通了。我将指示器的声明简单地更改为一个对象,然后从查询结果中删除了.enumerable (或.toList)。

感谢您的考虑和时间。

票数 -1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/55795077

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档