Reading Twitter Data with C# and LINQ

I wanted to read search results (tweets) using C#.  I started by deciding that a tweet looks something like this:

     public class Tweet
        public string Id { get; set; }
        public DateTime Published { get; set; }
        public string Link { get; set; }
        public string Title { get; set; }
        public Author Author { get; set; }
    public class Author
        public string Name { get; set; }
        public string Uri { get; set; }

Next I needed a way to get the data from the web and into a collection of Tweet’s.  I defined a TweetStream type that would handle the following:

  1. Downloading the data from
  2. Deserializing the Tweet data
  3. Remembering the high-watermark so that we always only get new tweets.

I stubbed out this:

     public class TweetStream
        private string m_refreshUri;
        List<Tweet> m_tweets;
        public TweetStream(string queryUri)
            m_refreshUri = queryUri;
            m_tweets = new List<Tweet>();
        public List<Tweet> Tweets
                return m_tweets;
        public void Refresh()
            // TODO - download tweet information from,
            // populate the tweet collection with the new
            // tweet data, and store the new high-watermark

Now I just need to fill in Refresh.

Download the results from Twitter

The LINQ XDocument type makes this very easy.  What’s not clear here is that I am loading ATOM data using the Twitter ATOM search API.  The result stream will look something like this:

 <?xml version="1.0" encoding="UTF-8"?>
<feed xmlns:google="" xml:lang="en-US" xmlns:openSearch="" xmlns="" xmlns:twitter="">
  <link type="text/html" rel="alternate" href=""/>
  <link type="application/atom+xml" rel="self" href=""/>
  <title>TFS - Twitter Search</title>
  <link type="application/opensearchdescription+xml" rel="search" href=""/>
  <link type="application/atom+xml" rel="refresh" href=";since_id=1152416895"/>
  <twitter:warning>adjusted since_id, it was older than allowed</twitter:warning>
  <link type="application/atom+xml" rel="next" href=";page=2&amp;q=TFS"/>
    <link type="text/html" rel="alternate" href=""/>
    <title>All day TFS training.</title>
    <content type="html">All day &lt;b&gt;TFS&lt;/b&gt; training.</content>
    <link type="image/png" rel="image" href=""/>
      <name>bubbafat (Robert Horvick)</name>

And we load it like this:

 XDocument feed = XDocument.Load(m_refreshUri);

Populate the Tweet Collection

With the document loaded we can now start pulling out the data we want.  First we need to define the ATOM namespace:

 XNamespace atomNS = "";

Next we need to iterate over every “entry” element in the feed and extract the data we care about.  LINQ makes this a breeze (though perhaps a bit tough to debug and grok at first).

 m_tweets = (from tweet in feed.Descendants(atomNS + "entry")
    select new Tweet
        Title = (string)tweet.Element(atomNS + "title"),
        Published = DateTime.Parse((string)tweet.Element(atomNS + "published")),
        Id = (string)tweet.Element(atomNS + "id"),
        Link = tweet.Elements(atomNS + "link")
            .Where(link => (string)link.Attribute("rel") == "alternate")
            .Select(link => (string)link.Attribute("href"))
        Author = (from author in tweet.Descendants(atomNS + "author")
            select new Author
                Name = (string)author.Element(atomNS + "name"),
                Uri = (string)author.Element(atomNS + "uri"),

Store the High-watermark

Finally we want to load the high watermark so we don’t ask for data twice.  This is just a matter of loading the “refresh” link from the top-level feed elements.

 m_refreshUri = feed.Descendants(atomNS + "link")
    .Where(link => link.Attribute("rel").Value == "refresh")
    .Select(link => link.Attribute("href").Value)

Putting it all Together

Not to put it all together you can create a collection of TweetStream’s and refresh them in a loop – printing out the tweets as you find them.

 using System;
using System.Threading;

using TwitterLib;
namespace TestHost
    class Program
        static void Main(string[] args)
            int totalTweets = 0;
            TweetStream[] tweetStreams = new TweetStream[] {
                new TweetStream(""),
                new TweetStream(""),
                new TweetStream(""),
                new TweetStream(""),
            while (true)
                int currentTweets = 0;
                bool newTweets = false;
                foreach (TweetStream stream in tweetStreams)
                    foreach(Tweet tweet in stream.Tweets)
                        Console.WriteLine("{0}: {1}",
                        newTweets = true;
                if (newTweets)
                    Console.WriteLine("Loaded {0} more tweets", currentTweets);
                    Console.WriteLine("Loaded {0} total tweets", totalTweets);
                    Console.WriteLine("No new tweets.");
                DateTime nextCheck = DateTime.Now.AddMinutes(5);
                Console.WriteLine("Will check again at {0}", nextCheck.ToShortTimeString());

You may have noticed I used a property (Author.TwitterId) that is not in the code – it’s just a simple Regex:

 public string TwitterId
        return s_idParser.Match(Name).Groups["twitterid"].Value;
private static Regex s_idParser = 
    new Regex(@"^(?<twitterid>.*)\s+\((?<displayname>.*)\)");

Whats’ Next?

To be clear this is not production-ready code.  It is very optimistic, quite inefficient and a bit ugly.  Also it doesn’t do anything terribly interesting.

But in less than 100 lines you have an ugly, slow, optimistic Twitter feed reader (which could read any ATOM stream with just a few additional lines).