How to return a list of Twitter tweets using LinqToTwitter in C#

Michael Roma on Oct 16, 2013

The following example shows how to use LinqToTwitter to return back tweets from a specific twitter handle.

First, download the LinqToTwitter library from http://linqtotwitter.codeplex.com/ and add the reference to your project

Let’s say you have your Twitter Developer API credentials stored in the web config and can be accessed through class called Config:

  • Config.TwitterConsumerKey
  • Config.TwitterConsumerSecret
  • Config.TwitterAccessToken
  • Config.TwitterAccessTokenSecret



Class that defines a single tweet:

public class Tweet
{
    public string Username { get; set; }
    public string FullName { get; set; }
    public string Text { get; set; }
    public string FormattedText { get; set; }
}

Function that returns back a list of tweets:

// function that returns the most recent tweets
public static List GetTweets(int max)
{	
	// get the auth
	var auth = new SingleUserAuthorizer
	{
		Credentials = new InMemoryCredentials
		{
			ConsumerKey = Config.TwitterConsumerKey,
			ConsumerSecret = Config.TwitterConsumerSecret,
			OAuthToken = Config.TwitterAccessToken,
			AccessToken = Config.TwitterAccessTokenSecret
		}
	};

	// get the context, query the last status
	var context = new TwitterContext(auth);
	var tweets =
		from tw in context.Status
		where
			tw.Type == StatusType.User &&
			tw.ScreenName == Config.TwitterHandle
		select tw;

	// handle exceptions, twitter service might be down
	try
	{
		// map to list
		return tweets
			.Take(max)
			.Select(t =>
				new Tweet
				{
					Username = t.ScreenName,
					FullName = t.User.Name,
					Text = t.Text,
					FormattedText = ParseTweet(t.Text)
				})
			.ToList();
	}
	catch (Exception) { }

	// return empty
	return new List();	
}

The following function will format the text to html and link up any handles, urls, and hash tags: (http://csharpmentor.blogspot.com/2011/12/parsing-twit-with-regex-in-c.html)