Search code examples
winformscollectionsc#-3.0generic-collections

Cannot convert type 'string' to 'System.Collections.ArrayList


Here is my code

   private static ArrayList GetFirstObjectFromDictionary(Dictionary<string, string> dictionary)
    {
        foreach (ArrayList arr in dictionary.Values) //error 
        {
            return arr;
        }
        return null;
    }

It causes error "Cannot convert type 'string' to 'System.Collections.ArrayList'".


Solution

  • You can use KeyValuePair for reach dictionary's items.

    private static ArrayList GetFirstObjectFromHashTable(Dictionary<string, string> dictionary)
    {
        ArrayList aLst = new ArrayList();
    
        foreach (KeyValuePair<string, string> pair in dictionary)
        {
            aLst.Add(pair.Value);
        }
    
        return aLst;
    }
    

    This page might help you to understand foreach using with dictionaries.