我试图对推文列表(类:SimpleTweet)进行排序,每个推文都有与之关联的ID(x.ID,其中x是类SimpleTweet的对象)。我正在使用linq对此进行排序,使用" OrderByDescending",但是在我设置List(Of SimpleTweet)类型的新对象等于排序列表的行上出现错误。我得到的错误是," System.InvalidCastException:无法转换类型为' System.Linq.OrderedEnumerable 2[SimpleTweet,System.Int64]' to type 'System.Collections.Generic.List
1 [SimpleTweet]'"的对象。
代码:
<WebMethod()> _
Public Function GetTweetsByUserID(ByVal userID As Integer) As List(Of SimpleTweet)
Dim result As New List(Of SimpleTweet)
Dim urlTwitter As String = "https://api.twitter.com/1/statuses/user_timeline.xml?include_entities=true&include_rts=true&screen_name={0}&count=3"
'Dim twitterfeed As String = utils.GetUserTwitterFeeds(userID, "docphin")
Dim lq As New lqDFDataContext
Dim var = lq.web_GetTweetsByUserID(userID).ToList()
Dim sortedresult As New List(Of SimpleTweet)
If Not var Is Nothing Then
For Each twitterfeed In var
Dim listURL As String = String.Format(urlTwitter, twitterFeed.TweeterFeed)
Dim tweetXML As XmlDocument = utils.GetXMLForURL(listURL)
Dim tweetnodelist As XmlNodeList = tweetXML.ChildNodes(1).ChildNodes
For Each node As XmlNode In tweetnodelist
Dim tweet As New SimpleTweet
tweet.CreatedAt = node.SelectSingleNode("created_at").InnerText
tweet.HTMLText = utils.ReturnTextWithHRefLink(node.SelectSingleNode("text").InnerText)
tweet.ID = node.SelectSingleNode("id").InnerText
tweet.Name = node.SelectSingleNode("user/name").InnerText
tweet.ScreenName = node.SelectSingleNode("user/screen_name").InnerText
tweet.Text = node.SelectSingleNode("text").InnerText
tweet.UserID = node.SelectSingleNode("user/id").InnerText
tweet.ProfileImageURL = node.SelectSingleNode("user/profile_image_url_https").InnerText
result.Add(tweet)
Next
Next
sortedresult = result.OrderByDescending(Function(tweet) tweet.ID)
End If
Return sortedresult
End Function
答案 0 :(得分:8)
您需要通过调用result
来实现.ToList()
。将它添加到此行的末尾:
sortedresult = result.OrderByDescending(Function(tweet) tweet.ID)
sortedResult
类型为List(Of SimpleTweet)
,OrderByDescending
返回IOrderedEnumerable(Of SimpleTweet)
,无法自动转换为预期类型。
答案 1 :(得分:3)
由于您要返回List(Of SimpleTweet)
,因此需要致电ToList
以从IEnumerable(Of SimpleTweet)
创建新列表:
Return sortedresult.ToList()
ToList
强制立即进行查询评估。