C# 访问IEnumerable的属性

C# 访问IEnumerable的属性,c#,twitter,ienumerable,tweetinvi,C#,Twitter,Ienumerable,Tweetinvi,我使用TweetInvi获取一组与指定标签匹配的tweet。我这样做的原因如下: var matchingTweets = Search.SearchTweets(hashtag); 这将返回一个IEnumerable(名为ITweet,是Tweet的接口),但是我无法创建Tweets的列表,因为Tweet是静态类型 相反,我创建了一个对象列表,使用: List<object> matches = matchingTweets.Cast<object>().ToList

我使用TweetInvi获取一组与指定标签匹配的tweet。我这样做的原因如下:

var matchingTweets = Search.SearchTweets(hashtag);
这将返回一个IEnumerable(名为
ITweet
,是
Tweet
的接口),但是我无法创建
Tweets
列表,因为
Tweet
是静态类型

相反,我创建了一个
对象列表
,使用:

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

使用
matches[i].ToString()
返回tweet内容,那么如何有效地将
matchingweets
中的结果强制转换到列表中,然后访问这些列表成员的属性?理想情况下,我希望避免使用
dynamic

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

可以这样访问它:

List<ITweet> tweets = matchingTweets.Take(5).ToList(); 
然后,您将能够访问您需要的内容。现在,如果需要在该函数的作用域之外共享此数据,请创建一个DTO对象并初始化它,而不是匿名类型

根据项目的大小和工作量,在任何情况下,当您与这样的外部服务交互时,创建一层DTO对象都是一种好的做法。然后,如果他们的模型发生了更改,则只能包含对DTO的更改


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

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

在上面的示例中,您试图从tweet中获取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
返回一个
ITweets
的IEnumerable,你可以访问任何一个定义的内容


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

您需要访问什么属性?无论
IEnumerable
中的类型是什么,都不能是静态的,这是不可能的。我可以访问MatchingWeets中的特定推文吗?如果您知道它的Id或其他一些信息,您可以使用LINQ。我更新了我的答案,告诉我如何通过id抓取一条tweet。仅此而已-我不知道任何tweet的id,但我想提取更新结果中前五条的id,以获取搜索
matchingweets.ElementAt(index)返回的前五条
@Wolfish-如果您想获取前5个的结果,请检查updateJust to note-您的答案也可以,但是@maccettura在TweetInvi的上下文中提供了一个答案,这在这里更为相关,因此选择他的答案作为“选择”答案。
var ids = matchingTweets.Take(5).Select(item => item.id).ToList();
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);