Reputation: 225
I am trying to make a program which haves a dictionary with words and their definitions separated by ':' and each word separated by '|' but for some reason when i print the Values of the dictionary i get System.Collection.Generic.List instead
Here is a possible input: "tackle: the equipment required for a task or sport | code: write code for a computer program | bit: a small piece, part, or quantity of something | tackle: make determined efforts to deal with a problem | bit: a short time or distance"
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);
}
}
}
}
Upvotes: 0
Views: 50
Reputation: 3761
First of all, you have to use item.Value
instead of item
to access your list of definitions.
You need to iterate through the definitions stored in your List<string>
:
foreach (var item in Dict)
{
foreach (var definition in item.Value)
{
Console.WriteLine(definition);
}
}
This will print a line for every definition in your lists. If you want to print all definitions in a single line, you can do the following instead:
foreach (var item in Dict)
{
Console.WriteLine(string.Join(", ", item.Value));
}
Upvotes: 1
Reputation: 43886
I'd actually expect the output to be a KeyValuePair<string, List<string>>
, because that's what you get as item
when you iterate through Dictionary<string, List<string>>
like you do in the line
foreach(var item in Dict)
You should change the output to something like:
Console.WriteLine(item.Key + ": " + string.Join(", " item.Value));
Upvotes: 5