I need to return an a generic list in the correct order for my project, and I’m getting InvalidCastException errors. Here is the code:
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)
Note that:
- CreateDate is a
Nullable(Of DateTimeOffset) - Sequence is a
Nullable(Of Int32) - SubSequence is a
Nullable(Of Int32)
The exact error I’m getting is:
Unable to cast object of type
‘System.Linq.OrderedEnumerable2[DTDataUploader.Comment,System.Int32]'1[DTDataUploader.Comment]’.
to type 'System.Collections.Generic.List
I’ve tried converting to the actual types…
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))
… but I get the same error. What am I missing here?
LINQ operations like
WhereandOrderByproduce queries, not results. As the error states, the result of your full LINQ expression is anOrderedEnumerable(Of DTDataUploader.Comment, System.Int32), not a list.To turn this into a list, add a call to
ToList()to the end of the expression.