Search code examples
c#arraylistcollectionssortedlist

Working with Collections - Arraylist , Sorted list, Dictionaryentry


Below is my Code : The problem is when I am adding SortedList collection to Arraylist and at the time of retrieval it(SortedList) converts to DictonaryEntry Strange. Can anybody explain? Thanks in advance :)

public partial class WebForm1 : System.Web.UI.Page
{
    ArrayList al = new ArrayList();

    protected void Page_Load(object sender, EventArgs e)
    {

        al.Add('a');
        al.Add(true);
        al.Add(new ParentClass().MyProperty = 10);
        al.Add("ABCD");
        al.Add(3.00M);

        ArrayList al1 = new ArrayList();
        al1.Add("al1 array list");
        al1.AddRange(al);
        SortedList sl = new SortedList();
        sl.Add(1, "sandeep");
        al1.AddRange(sl); // Here I have added sorted list to Arraylist

        foreach (object item in al1)
        {
            //---- The below code dont run properly (don't give desired output) , it gives output as System.Collections.DictionaryEntry
            if (item is SortedList)
            {
                for (int i = 0; i < ((SortedList)item).Count; i++)
                {
                    Response.Write(((SortedList)item).GetByIndex(i));
                }

            }

            //// --- Below code run perfectly. and I get the desired output.
            //if (item is DictionaryEntry)
            //    Response.Write(((DictionaryEntry)item).Value);
            else
                Response.Write(item);

            Response.Write("<br/>");
        }
    }

}

Solution

  • SortedList is not a list - it's a dictionary that acts like a list. It is enumerated like a dictionary - by key-value pairs. So when you al1.AddRange(s1); you add the key-value pairs that compose the sorted list.

    If you wanted to add the actual values of the SortedList you should have al1.AddRange(s1.Values);, but seeing that you want to add the SortedList object itself, what you should do is al1.Add(s1);.