访问 IEnumerable 的属性

Accessing the properties of an IEnumerable

我正在使用 TweetInvi 获取一堆与指定主题标签匹配的推文。我用以下方法做到这一点:

var matchingTweets = Search.SearchTweets(hashtag);

这个 returns 一个 IEnumerable(名为 ITweetTweet 的接口),但是我无法创建 TweetsList<>,因为 Tweet 是静态类型。

我制作了一个 objects 列表,使用:

List<object> matches = matchingTweets.Cast<object>().ToList();

但是,尽管 matchingTweets IEnumerable 的每个成员都有许多属性,但我无法使用以下方法访问它们:

long tweetID = matches[i].<property>;

使用 matches[i].ToString() returns 推文内容,那么如何有效地将 matchingTweets 中的结果转换为列表,然后访问这些列表成员的属性?理想情况下,我想避免使用 dynamic.

您无法访问这些属性是有道理的。您将其转换为 object,因此您只能访问 object 的属性和方法(如您所说,可能已被覆盖)。

直接访问应该没问题:

List<ITweet> tweets = matchingTweets.Take(5).ToList(); 

你可以做的是将它投射到你的新对象上:

var tweets = matchingTweets.Select(item => new {
                                       property1 = item.property1,
                                       property2 = item.property2
                                   })
                           .Take(5).ToList();

然后您将能够访问您需要的内容。现在,如果您需要在该函数范围之外共享此数据,请创建一个 DTO 对象并初始化它而不是匿名类型。

根据项目的大小和工作量,在任何情况下,当您与这样的外部服务交互时,创建一层 DTO 对象通常是一个很好的做法。然后,如果他们的模型发生变化,您可以仅将更改包含在 DTO 中。


如果您只需要前 5 个的 ID,那么:

var ids = matchingTweets.Take(5).Select(item => item.id).ToList();

在上面的示例中,您试图从推文中获取 ID。 ITweet 实现了包含 Id 属性 的 ITweetIdentifier。您实际上可以通过以下方式访问它:

var matchingTweets = Search.SearchTweets(hashtag);

//Grab the first 5 tweets from the results.
var firstFiveTweets = matchingTweets.Take(5).ToList();

//if you only want the ids and not the entire object
var firstFiveTweetIds = matchingTweets.Take(5).Select(t => t.Id).ToList();

//Iterate through and do stuff
foreach (var tweet in matchingTweets)
{
    //These are just examples of the properties accessible to you...
    if(tweet.Favorited)
    {
        var text = tweet.FullText;
    }     
    if(tweet.RetweetCount > 100)
    {
        //TODO: Handle popular tweets...
    }   
}

//Get item at specific index
matchingTweets.ElementAt(index);

我不知道你想用所有信息做什么,但由于 SearchTweets returns ITweets 的 IEnumerable 你可以访问任何 ITweet 已定义。

我强烈建议您浏览一下他们的 wiki。它组织得很好,并为您提供了一些基本任务的清晰示例。