Go Premium for a chance to win a PS4. Enter to Win

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 932
  • Last Modified:

Cannot convert from object to string, dictionary c#

try to add arraylist from array and add into dictionary (string and integer) and finally sort the value of the dictionary.

while adding to dictionary, getting
'cannot convert from objecct to string.'


static void Main(string[] args)
        {
            string[] strArray = { "A", "B", "C" };
            int[] intArray = { 3, 2, 1 };

            ArrayList alstr = new ArrayList();
            ArrayList alint = new ArrayList();

            for (int m = 0; m < strArray.Length; m++)
            {
                alstr.Add(strArray[m]);
            }

            for (int n = 0; n < intArray.Length; n++)
            {
                alint.Add(intArray[n]);
            }

            object[] myStringArray = alstr.ToArray();
            object[] myIntArray = alint.ToArray();

            var dict = new Dictionary<string, int>();

            //foreach (string strArray01 in strArray)
            //{
            //    foreach (int intArra01 in intArray)
            //    {
            //        dict.Add(strArray01, intArra01);
                    
            //        break;

            //    }

            //}

            for (int o = 0; o < myStringArray.Length; o++)
            {
                dict.Add(myStringArray[o], myIntArray[o]);
            }

            //for (int i = 0; i < strArray.Length; i++)
            //{
            //    dict.Add(strArray[i], intArray[i]);

            //}
                var items = from k in dict.Keys
                            orderby dict[k] ascending
                            select k;


            


            foreach (string kv in items)
            {

                Console.WriteLine("Key : {0}, Value : {1}", kv, dict[kv]);

            }

            Console.ReadLine();

        }
    }

Open in new window

0
doramail05
Asked:
doramail05
1 Solution
 
Mike TomlinsonMiddle School Assistant TeacherCommented:
Try changing:

    dict.Add(myStringArray[o], myIntArray[o]);

To:

    dict.Add((string)myStringArray[o], (int)myIntArray[o]);
0
 
Subrat (C++ windows/Linux)Software EngineerCommented:
FYI:
To increase the perfermance use List<T> instead of ArrayList
0

Featured Post

What does it mean to be "Always On"?

Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now