我正在尝试对推文列表(类: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
最佳答案
您需要通过调用result
来实现.ToList()
。将其添加到此行的末尾:
sortedresult = result.OrderByDescending(Function(tweet) tweet.ID)
sortedResult
的类型为List(Of SimpleTweet)
,而OrderByDescending
返回的IOrderedEnumerable(Of SimpleTweet)
无法自动转换为所需的类型。关于vb.net - 尝试使用linq排序对象列表时,获取无效的强制转换异常,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/11971683/