Joe Wood's Blog

Technology

<October 2008>
SuMoTuWeThFrSa
2829301234
567891011
12131415161718
19202122232425
2627282930311
2345678


Navigation

Subscriptions



Tuesday, June 21, 2005 - Posts

VS2005 Cool Feature #3 - New Collections

There are a lot of changes to Collections in Whidbey.  I'll highlight some of the changes here:

The generic interface IList can be used to house any collection, including arrays.

  IList<string> stringList = null; 
  string[] stringArray = new string[] { "one", "two", "three", "four" }; 
  stringList = stringArray;

IList includes methods for removing and adding, but these are invalid when the IList points to an array.  To check if you can manipulate the IList there's a IsReadOnly property:
  

  if (stringList.IsReadOnly) 
  { 
       Console.WriteLine("Readonly");
  }

The List<> collection can be used like ArrayList.  In this case we create a new collection based on our array.  The List<> can be manipulated. 
  

  stringList = new List<string>(stringList); 
  if (!stringList.IsReadOnly) 
  { 
      stringList.RemoveAt(0);
      Console.WriteLine("Can modify");
  } 

Another cool new feature is the ForEach method.  The example below uses ForEach and an anonymous delegate to set-up a dictionary from the contents of our list.  IList<> doesn't support ForEach, only the List<> class supports it.  

  List<string> stringList2 = new List<string>(stringList);
  string oneString; 
  IDictionary<string,string> stringDictionary = new Dictionary<string,string>(); 
  stringList2.ForEach(delegate(string item) { stringDictionary.Add(item, item); });

Another cool feature is the ability to test for an item in a dictionary and return it in one go.  This is much more efficient than doing the double look-up in .NET 1.1:
 

  if (stringDictionary.TryGetValue("two", out oneString)) 
  { 
      Console.WriteLine("Got value in one go " + oneString);
  }

 

posted Tuesday, June 21, 2005 8:05 AM by joewood with 1 Comments




Powered by Dot Net Junkies, by Telligent Systems