You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C#字典嵌套列表使用问题:Add方法报错与输出格式求助

问题解决:字典存储食物列表与格式化输出

核心问题修正

  1. Dictionary.Add方法参数错误
    Dictionary<string, List<string>>的Add方法仅接受键和**对应的值(List)**两个参数,你传入三个参数必然报错。此外需要注意:要把输入中从第2个元素开始的所有内容作为食物列表,而非仅取前两个食物。

  2. 重复人名的处理
    如果同一个人名多次输入食物,直接调用Add会因键重复抛出异常。需要先判断字典中是否已存在该人名:

  • 存在:将新食物追加到已有列表
  • 不存在:添加新的键值对
  1. 格式化输出实现
    遍历字典时,用string.Join(", ", 食物列表)将列表转为逗号分隔的字符串,再拼接成{人名} -> {食物1}, {食物2}...的格式。

修正后的完整代码

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

namespace stack1
{
    class Program
    {
        static void Main(string[] args)
        {
            string input = Console.ReadLine();
            Dictionary<string, List<string>> peopleFood = new Dictionary<string, List<string>>();
            
            while (input != "stop")
            {
                List<string> inputs = input.Split(" ").ToList();
                // 过滤无效输入(至少需要人名+一个食物)
                if (inputs.Count >= 2)
                {
                    string personName = inputs[0];
                    // 获取所有食物(跳过第一个元素:人名)
                    List<string> foods = inputs.Skip(1).ToList();
                    
                    if (peopleFood.ContainsKey(personName))
                    {
                        // 追加新食物到已有列表
                        peopleFood[personName].AddRange(foods);
                    }
                    else
                    {
                        // 新增人名与对应食物列表
                        peopleFood.Add(personName, foods);
                    }
                }
                input = Console.ReadLine();
            }
            
            // 按要求格式输出
            foreach (var entry in peopleFood)
            {
                string foodString = string.Join(", ", entry.Value);
                Console.WriteLine($"{entry.Key} -> {foodString}");
            }
        }
    }
}

关键代码说明

  • inputs.Skip(1).ToList():跳过输入分割后的第一个元素(人名),自动收集后续所有食物,支持任意数量的食物输入。
  • ContainsKey判断:避免重复键引发的异常,保证同一个人的食物可以多次追加。
  • string.Join(", ", entry.Value):快速将List类型的食物列表转换为逗号分隔的字符串,满足输出格式需求。

内容的提问来源于stack exchange,提问作者Martin Kulev

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.18 10:35:41