1

我需要以正确的顺序为我的项目返回一个通用列表,并且我收到 InvalidCastException 错误。这是代码:

Dim lDt As List(Of Comment) = RemapCommentsForE1(so.CommentList). _
OrderBy(Function(x) x.CreateDate.Value). _
ThenBy(Function(x) x.Sequence). _
ThenBy(Function(x) x.SubSequence)

注意:

  • CreateDate 是一个Nullable(Of DateTimeOffset)
  • 序列是一个Nullable(Of Int32)
  • 子序列是一个Nullable(Of Int32)

我得到的确切错误是:

无法转换类型为“System.Linq.OrderedEnumerable 2[DTDataUploader.Comment,System.Int32]' to type 'System.Collections.Generic.List1 [DTDataUploader.Comment]”的对象。

我已经尝试转换为实际类型...

Dim lDt As List(Of Comment) = RemapCommentsForE1(so.CommentList). _
OrderBy(Function(x) x.CreateDate.Value). _
ThenBy(Function(x) Convert.ToInt32(x.Sequence)). _
ThenBy(Function(x) Convert.ToInt32(x.SubSequence))

...但我得到同样的错误。我在这里想念什么?

4

2 回答 2

2

LINQ 操作喜欢WhereOrderBy产生查询,而不是结果。如错误所述,完整 LINQ 表达式的结果是OrderedEnumerable(Of DTDataUploader.Comment, System.Int32),而不是列表。

要将其转换为列表,请将调用添加到ToList()表达式的末尾。

Dim lDt As List(Of Comment) = RemapCommentsForE1(so.CommentList). _
OrderBy(Function(x) x.CreateDate.Value). _
ThenBy(Function(x) x.Sequence). _
ThenBy(Function(x) x.SubSequence).ToList()
于 2012-06-13T18:51:00.760 回答
0

查询的结果是一个OrderedEnumerable,只需.ToList()在末尾添加即可实现结果为列表。

于 2012-06-13T18:50:46.103 回答