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

Posted on October 16, 2013 by Michael Roma

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

First, download the LinqToTwitter library from 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
			tw.Type == StatusType.User &&
			tw.ScreenName == Config.TwitterHandle
		select tw;

	// handle exceptions, twitter service might be down
		// map to list
		return tweets
			.Select(t =>
				new Tweet
					Username = t.ScreenName,
					FullName = t.User.Name,
					Text = t.Text,
					FormattedText = ParseTweet(t.Text)
	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: (

comments powered by Disqus