0

I am trying to print each key and value from the QandA_Dictionary shown below, but I keep getting System.int32[] instead of the actual values I have listed. Could someone please point me in the right direction of resolving this issue?

using System;
using System.Collections;
using System.Collections.Generic;

namespace DictionaryPractice
{
    class MainClass
    {
        public static void Main(string[] args)
        {

            Dictionary<string, int[]> QandA_Dictionary = new Dictionary<string, int[]>();
            QandA_Dictionary.Add("What is 1 + 1?", new int[] { 1, 2, 3, 4 });
            QandA_Dictionary.Add("What is 1 + 2?", new int[] { 1, 2, 3, 4 });
            QandA_Dictionary.Add("What is 1 + 3?", new int[] { 1, 2, 3, 4 });
            QandA_Dictionary.Add("What is 1 + 4?", new int[] { 2, 3, 4, 5 });
            foreach (var pair in QandA_Dictionary)
            {
                Console.WriteLine("{0},{1}", pair.Key, pair.Value);
            }
            Console.ReadKey();
        }
    }
}
0

3 Answers 3

3

This would be the simplest change:

Dictionary<string, int[]> QandA_Dictionary = new Dictionary<string, int[]>();
QandA_Dictionary.Add("What is 1 + 1?", new int[] { 1, 2, 3, 4 });
QandA_Dictionary.Add("What is 1 + 2?", new int[] { 1, 2, 3, 4 });
QandA_Dictionary.Add("What is 1 + 3?", new int[] { 1, 2, 3, 4 });
QandA_Dictionary.Add("What is 1 + 4?", new int[] { 2, 3, 4, 5 });
foreach (var pair in QandA_Dictionary)
{
    Console.WriteLine("{0},{1}", pair.Key, String.Join(", ", pair.Value));
}
Console.ReadKey();
Sign up to request clarification or add additional context in comments.

Comments

2

You can use string.Join to convert your array into a string

Console.WriteLine("{0},{1}", pair.Key, string.Join(",", pair.Value));

Comments

-1
        var qandADictionary = new Dictionary<string, int[]>
        {
            {"What is 1 + 1?", new[] {1, 2, 3, 4}},
            {"What is 1 + 2?", new[] {1, 2, 3, 4}},
            {"What is 1 + 3?", new[] {1, 2, 3, 4}},
            {"What is 1 + 4?", new[] {2, 3, 4, 5}}
        };
        foreach (var pair in qandADictionary)
        {
            var stringArray = Array.ConvertAll(pair.Value, i => i.ToString());
             Console.WriteLine(string.Format("{0},{1}", pair.Key, string.Join(" ", stringArray)));
        }
        Console.ReadKey();

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.