Tuesday, October 16, 2007 3:26 PM Ryan Ternier

A Quick refresher on List<T>

I'm a big fan of .NET Generics. In fact, I can't believe I lived without them in .NET 1.1.  Generics are pretty much the most powerful feature for C# 2.0. They allow you to define type safe data structures. They give a huge boost in performance, and they allow us to move away from DataTables and DataSets when it comes to collections of standard data.

Microsoft's MSDN has a great article that explains more about generics. You can find it here.

What I intend to give you in this short blog is a quick refresher on the List<T>. I've always loved this strongly typed list, and I cannot work without it.

Let's take the class Ninja (Now remember there's a whole lot more to Ninjas than just their age and name):
*Note this isn't the best made class, so please don't quote me on this one :P

 

   71     public class Ninja

   72     {

   73         public int _age;

   74         public string _name;

   75 

   76         public Ninja(int age, string name)

   77         {

   78             this._age = age;

   79             this._name = name;

   80         }

   81     }


I'm now going to manually add a few Ninjas to my List:

   18             //Let's create our List.

   19             //Remember this uses    System.Collection.Generic

   20             List<Ninja> ninjas = new List<Ninja>();

   21 

   22             ninjas.Add(new Ninja(26, "Ryan Ternier"));

   23             ninjas.Add(new Ninja(23435, "You"));

   24             ninjas.Add(new Ninja(0, "Ryan's New Kid"));

   25             ninjas.Add(new Ninja(4, "Xana"));

   26             ninjas.Add(new Ninja(4, "Hobbs"));

   27             ninjas.Add(new Ninja(-1, "Trogdor"));

 I now have a Type Safe List. This list is a high efficiency killing machine... literally.

I'm going to use a StringBuilder to hold my HTML. If you don't understand why, please be patient and look at this post regarding string efficiency.

Let's see some code!

 

   29 //now let's have some fun.

   30             System.Text.StringBuilder sb = new System.Text.StringBuilder();

   31             sb.Append("<h1>List As Is</h1> using ForEach<br/> ");

   32             sb.Append("<br/><ul>");

   33             ninjas.ForEach(delegate(Ninja n)

   34             {

   35                 sb.Append(String.Format("<li>{0}, ({1})</li>", n._name, n._age));

   36             });

   37             sb.Append("</ul><br/>");

   38 

   39             ///////////////////////////////////////

   40             sb.Append("<h1>Age is greater or equal to 0</h1>using FindAll,and foreach<br/> ");

   41             sb.Append("<br/><ul>");

   42             List<Ninja> thoseAlive = ninjas.FindAll(delegate(Ninja n)

   43             {

   44                 return n._age >= 0;

   45             });

   46             thoseAlive.ForEach(delegate(Ninja n)

   47             {

   48                 sb.Append(String.Format("<li>{0}, ({1})</li>", n._name, n._age));

   49             });

   50             sb.Append("</ul><br/>");

   51             ////////////////////////////////////////

   52             sb.Append("<h1>let's Sort Them</h1>using Sort<br/> ");

   53             sb.Append("<br/><ul>");

   54             ninjas.Sort(delegate(Ninja n1, Ninja n2)

   55             {

   56                 return n1._name.CompareTo(n2._name);

   57             });

   58             ninjas.ForEach(delegate(Ninja n)

   59             {

   60                 sb.Append(String.Format("<li>{0}, ({1})</li>", n._name, n._age));

   61             });

   62             sb.Append("</ul><br/>");

   63             /////////////////////////////////////////

   64             lblTest.Text = sb.ToString();

 There are many more functions on each List in the Generics Namespace. Most of them function the same as you see above. I would recommend getting your head wrapped around delegates because as soon as VS 2008 comes out they will be your best friend.

Ok, let's look at the output.


 

You can see how nice they are. What is especially nice is when you have a List<t> of objects that have their own List<t> of more objects. Generics make it very easy to work with and play with these.

 

Remember that C# is also Managed Code, which means you can do the following: 

   83     public class FemaleNinja : Ninja

   84     {

   85         public string _husband;

   86 

   87         public FemaleNinja(string husband, int age, string name)

   88             : base(age, name)

   89         {

   90             this._husband = husband;

   91         }

   92     }

 Let's add it to the String Builder. I'll use a regular ForEach here, checking the type of each "ninja" in my List.

   65             FemaleNinja femaleNinja = new FemaleNinja("Ryan", 29, "Ange");

   66             ninjas.Add(femaleNinja);

   67             sb.Append("<h1>Get all Female Ninja</h1>using Foreach<br/> ");

   68             sb.Append("<br/><ul>");

   69             ninjas.ForEach(delegate(Ninja n)

   70             {

   71                 if(n.GetType() == typeof(FemaleNinja))

   72                     sb.Append(String.Format("<li>{0}, ({1})</li>", n._name, n._age));

   73             });

   74             sb.Append("</ul><br/>");

   75             sb.Append("</ul><br/>");

   76 

   77             lblTest.Text = sb.ToString();

 And here we go!

Filed under: , , , ,

Comments

# re: A Quick refresher on List<T>

Tuesday, October 16, 2007 7:29 PM by Joe Chung

People who use StringBuilders to construct HTML make me ill. :P

# re: A Quick refresher on List<T>

Tuesday, October 16, 2007 7:49 PM by foobar

if (p is FemaleNinja) is a little less obtuse.

# re: A Quick refresher on List<T>

Wednesday, October 17, 2007 1:39 AM by Ryan Anderson

Probably one of the most simplistic and straight forward blog post describing generics that I have read to date! (and I didn't start reading blogs yesterday either... :) )

Thanks!

# re: A Quick refresher on List<T>

Wednesday, October 17, 2007 8:15 AM by Steven Smith

Use sb.AppendFormat rather than sb.Append(String.Format)

# re: A Quick refresher on List<T>

Wednesday, October 17, 2007 11:03 AM by Ryan Ternier

@Joe Chung:

String Builders are more efficient than regular strings. and for this example they did what I needed to do :)

@foobar

Yes you are right. that is less obtuse - thank you for reminding me of that :)

@Ryan Anderson

Thanks you.

@Steven Smith

You know I didn't even check to see if the stringbuilder had that method. Thanks for bringing it to my attention :)

Leave a Comment

(required) 
(required) 
(optional)
(required)