Search code examples
c#twitterienumerabletweetinvi

Accessing the properties of an IEnumerable


I'm using TweetInvi to grab a bunch of tweets that match a specified hashtag. I do this with the following:

var matchingTweets = Search.SearchTweets(hashtag);

This returns an IEnumerable (named ITweet, interface of Tweet), however I cannot create a List<> of Tweets, because Tweet is a static type.

I made, instead, a list of objects, using:

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

However, although each member of the matchingTweets IEnumerable has a number of properties, I cannot access them using:

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

Using matches[i].ToString() returns the tweet content, so how can I effectively cast the results in matchingTweets to a list, and subsequently access the properties of those list members? I would ideally like to avoid using dynamic.


Solution

  • In your example above you were trying to grab the ID from the tweet. ITweet implements ITweetIdentifier which contains the Id property. You can literally just access it by:

    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);
    

    I don't know exactly what you want to do with all the info, but since the SearchTweets returns a IEnumerable of ITweets you have access to anything an ITweet has defined.

    I highly recommend looking through their wiki. It's pretty well organized and gives you clear examples of some basic tasks.