Sunday, April 11, 2010

SortedList in .net

SortedList



  • Represents a collection of key-and-value pairs that are sorted by the keys and are accessible by key and by index.

  • In one of my program, I wanted to sort my values based on the keys, so I find out that SortedList is the best way of doing it.

  • SortedList is a hybrid between a Hashtable and an Array.

  • Operations on a SortedList tend to be slower than operations on a Hashtable because of the sorting.

  • SortedList offers more flexibility by allowing access to the values either through the associated keys or through the indexes.


Example:


public SortedList itemSetOneSL;

itemSetOneSL = new SortedList();

for(int i=5;i>0;i--)

{

if (!itemSetOneSL.Contains("C"+i.ToString())
{
itemSetOneSL.Add("C"+i.ToString(), i);
}
}

StreamWriter strWriter = new StreamWriter("test.txt");

foreach (var item in itemSetOneSL.Keys)
{

strWriter.WriteLine(item.ToString() + " " + itemSetOneSL[item.ToString()]);

}

strWriter.Close();
strWriter.Dispose();

No comments:

Post a Comment