如何打印此数组中的字典值而不是 System.int32[]

本文关键字:System int32 字典 何打印 打印 数组 | 更新日期: 2023-09-27 17:56:01

我正在尝试打印下面显示QandA_Dictionary中的每个键和值,但我不断得到System.int32[]而不是我列出的实际值。有人可以指出我解决此问题的正确方向吗?

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();
        }
    }
}

如何打印此数组中的字典值而不是 System.int32[]

这将是最简单的更改:

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();
您可以使用

string.Join将数组转换为字符串

Console.WriteLine("{0},{1}", pair.Key, string.Join(",", pair.Value));
        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();
相关文章: