MFC and .NET Explorations

05 December 2006

Handy Collections

  • Generic key/value pair collection that automatically sorts based on the key:
    SortedList<TKey,TValue>
  • Same as above but without the automatic sorting and better performance with large number of items:
    Dictionary<TKey,TValue>

http://msdn2.microsoft.com/en-us/library/5tbh8a42.aspx


Declare either of them it as follows:

        public SortedList<int, Antenna> antennas;

To iterate through it:

        for each (KeyValuePair<int, Antenna^> kvp in rigging->antennas)
        {
            Antenna^ antenna = kvp.Value;
 
            CString antennaId;
            antennaId.Format(_T("%d"), kvp.Key);
 
            (...)
        }
 

  • I'm using key/value pair collections because I want to be able to retrieve an element given its key. But it is possible to perform much more complex retrievals in a very elegant way. Anything that implements IEnumerable can be searched.