2014-10-01 51 views
0

下面是我的代碼:問題是當我將ArrayList列表添加到Arraylist並且在檢索它時(SortedList)轉換爲DictonaryEntry Strange。有人可以解釋嗎?在此先感謝:)使用集合 - Arraylist,Sorted list,Dictionaryentry

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/>"); 
     } 
    } 

} 

回答

0

SortedList不是一個列表 - 它是一個像列表一樣的字典。它被像一個字典枚舉 - 通過鍵值對。所以當你al1.AddRange(s1);你添加組成排序列表的鍵值對。

如果你想添加你應該有al1.AddRange(s1.Values);SortedList的實際值,但看到要添加SortedList對象本身,你應該做的是al1.Add(s1);