【问题标题】:Dictionary contains list adress instead of list values C#字典包含列表地址而不是列表值 C#
【发布时间】:2019-05-13 19:39:48
【问题描述】:

我正在尝试制作一个程序,它有一个包含单词的字典,它们的定义用“:”分隔,每个单词用“|”分隔但由于某种原因,当我打印字典的值时,我得到 System.Collection.Generic.List

这里有一个可能的输入:“tackle:一项任务或运动所需的设备 | code:为计算机程序编写代码 | bit:一小块、部分或数量的东西 | 解决:下定决心去处理有问题|位:短时间或距离”

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Ex1_Dictionary
{
    class Program
    {
        static void Main(string[] args)
        {
            var Input = Console.ReadLine().Split(':', '|').ToArray();
            var Words = new List<string>();
            var Dict = new Dictionary<string, List<string>>();
            for (int i = 0; i < Input.Length; i+=2)
            {
                string word = Input[i];
                string definition = Input[i + 1];
                word = word.TrimStart();
                definition = definition.TrimStart();
                Console.WriteLine(definition);
                if (Dict.ContainsKey(word) == false)
                {
                    Dict.Add(word, new List<string>());
                }
                Dict[word].Add(definition);
            }
            foreach (var item in Dict)
            {
                Console.WriteLine(item);
            }
        }
    }
}

【问题讨论】:

    标签: c# list dictionary for-loop


    【解决方案1】:

    首先,您必须使用item.Value 而不是item 来访问您的定义列表。

    您需要遍历存储在您的List&lt;string&gt; 中的定义:

    foreach (var item in Dict)
    {
        foreach (var definition in item.Value) 
        {
            Console.WriteLine(definition);
        }
    }
    

    这将为列表中的每个定义打印一行。如果您想在一行中打印所有定义,您可以执行以下操作:

    foreach (var item in Dict)
    {
        Console.WriteLine(string.Join(", ", item.Value));
    }
    

    【讨论】:

      【解决方案2】:

      我实际上希望输出是KeyValuePair&lt;string, List&lt;string&gt;&gt;,因为当您像在行中那样遍历Dictionary&lt;string, List&lt;string&gt;&gt; 时,这就是item 得到的结果

      foreach(var item in Dict)
      

      您应该将输出更改为:

      Console.WriteLine(item.Key + ": " + string.Join(", " item.Value)); 
      

      【讨论】:

        【解决方案3】:

        为什么不拆分(“|”)。那么,foreach、split(":")?

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2016-02-26
          • 1970-01-01
          • 1970-01-01
          • 2020-05-09
          • 2021-05-10
          • 1970-01-01
          • 1970-01-01
          • 2016-11-23
          相关资源
          最近更新 更多