7

我正在尝试对推文列表(类: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.List1 [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
4

2 回答 2

10

您需要通过result调用来实现.ToList(). 将其添加到此行的末尾:

sortedresult = result.OrderByDescending(Function(tweet) tweet.ID)

sortedResult是类型List(Of SimpleTweet)OrderByDescending返回一个IOrderedEnumerable(Of SimpleTweet)不能自动转换为预期类型的​​。

于 2012-08-15T14:58:38.917 回答
3

由于您要返回 aList(Of SimpleTweet)您需要调用ToList以从以下位置创建一个新列表IEnumerable(Of SimpleTweet)

Return sortedresult.ToList()

ToList 强制立即进行查询评估。

于 2012-08-15T14:58:50.747 回答