Using Custom Lists in C#

22 03 2010

Recently I needed to retrieve information from a database and store it during runtime so that I could do some data manipulation and then present the data in a PDF file. When doing something like this, I find it very useful to use a custom list. I create a class that has all the properties I require, and then I create a list using this class as it’s type. All my data can then be stored neatly in this list and it’s easy to keep track of everything. Here’s some code to show how I do this.

1:Create your class…

private class RowForPDF
public string FirstName;
public string Surname;
public string PercCompleted;
public string CompletionDate;
public RowForPDF(string firstName, string surname, string percCompleted, string completionDate)
this.FirstName = firstName;
this.Surname = surname;
this.PercCompleted = percCompleted;
this.CompletionDate = completionDate;
public RowForPDF(string surname, string firstName)
this.Surname = surname;
this.FirstName = firstName;

As you can see, in my class I have overloaded it so I can have different types of my class depending on what my list is needed for.

2: Declare your list…
private List<RowForPDF> usersCompleted = new List<RowForPDF>();
private List<RowForPDF> userList = new List<RowForPDF>();

3: Add data to your list…
usersCompleted.Add(new RowForPDF("Sarah", "Williams", "52", "22/03/2010"));
userList.Add(new RowForPDF("Williams", "Sarah"));

You then have all your data stored in lists. Woop! And accessing them is nice too. For example, if I wanted to loop through each user in userCompleted and store some of their information in userList, I could do it like this…

for(int i = 0; i < usersCompleted.Count; i++)
userList.Add(new RowForPDF(usersCompleted[i].Surname, usersCompleted[i].Firstname));

Also when you’ve finished with the data in the list, you can use the Clear() method and it will remove all elements from your list.

So there they are, aren’t they beautiful?




Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: