gpt4 book ai didi

vb.net - 尝试使用 linq 对对象列表进行排序时出现无效的强制转换异常

转载 作者:行者123 更新时间:2023-12-04 17:11:17 25 4
gpt4 key购买 nike

我正在尝试对推文列表(类: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)
sortedResultList(Of SimpleTweet) 类型和 OrderByDescending返回 IOrderedEnumerable(Of SimpleTweet)不能自动转换为预期的类型。

关于vb.net - 尝试使用 linq 对对象列表进行排序时出现无效的强制转换异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11971683/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com