The List in C# - Digital Tool Factory blog The List in C# - Digital Tool Factory blog

The List in C#

The first entry in my Code Review is the List<>.

So far, the List is my favorite sort of array in C#.  It has the benefits of

  • being obvious in naming
  • you do not have to know the size when it is declared – the List can expand or contract as needed
  • adding items to the array is quite simple, as is looping through the array
  • finding items in the list is easy as well

The basic List syntax is this

List<string> lstContactList = new List<string>();

At first the syntax looks a bit off, what with the odd angle brackets<> and the () at the very end of the declaration, but that is the only counter-intuitive part of the List.  Please note, a list can hold any type of object or type, not just strings.

To add to the list simply use the .Add syntax, for example

lstContactList.Add (“Bob Raindorf”);.

You can find the index of a particular list item by simply using this syntax:

lstContactList.IndexOf(“Bob Raindorf”);

Once you identify the  identified, you can replace the value of the list item quite simply by

lstContactList[lstContactList.IndexOf(“Bob Raindorf”)] = “Robert Raindorf”;

If you want to loop through the list, just do this

foreach (string str in lstContactList)
{
InsertToDB(str);
}

To clear the list, just do this

lstContactList.Clear();

That’s all I need to remember (for now anyway), hopefully the act of writing this pushed it into long term memory.

 

This post originally appeared on the Stronico blog – with the absorption of Stronico into Digital Tool Factory this post has been moved to the Digital Tool Factory blog

 

Written By Steve French

 

Leave a Reply

Your email address will not be published. Required fields are marked *






Copyright 2011 Digital Tool Factory. All Rights Reserved. Powered by raw technical talent. And in this case, WordPress.