OrderBy抛出InvalidCastException的泛型列表中的可空属性

时间:2012-06-13 18:48:09

标签: .net vb.net lambda nullable

我需要以正确的顺序为我的项目返回一个通用列表,并且我收到了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)
  • SubSequence是Nullable(Of Int32)

我得到的确切错误是:

  

无法投射类型的对象   'System.Linq.OrderedEnumerable 2[DTDataUploader.Comment,System.Int32]' to type 'System.Collections.Generic.List 1 [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))

...但我得到了同样的错误。我在这里缺少什么?

2 个答案:

答案 0 :(得分:2)

WhereOrderBy等LINQ操作会生成查询,而非结果。正如错误所述,完整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()

答案 1 :(得分:0)

查询结果为OrderedEnumerable,只需在末尾添加.ToList()即可将结果显示为列表。

相关问题