Reputation: 35
I have the following code snippet to add string values to a List and then add the list as the key in a dictionary. Now I want to print both the key and the value from the Dictionary but I'm unable to do so. Any ideas or suggestions will be appreciated.
Dictionary<List<string>, int> dic = new Dictionary<List<string>, int>();
List<string> mylist = new List<string>();
string[] str = new string[5];
int counter = 0;
for (int i = 0; i < 5; i++)
{
Console.Write("Type Number:");
string test = Console.ReadLine();
mylist.Add(test);
counter++;
}
Console.WriteLine(string.Join(",", mylist));
dic.Add(mylist, counter);
Upvotes: 1
Views: 10164
Reputation: 30813
If you want to have string
as you key
(as you indicate by joining the List<string>
, then consider making a Dictionary<string,int>
instead of Dictionary<List<string>,int>
:
Dictionary<string, int> dic = new Dictionary<string, int>(); //note this dict type
List<string> mylist = new List<string>();
string[] str = new string[5];
int counter = 0;
for (int i = 0; i < 5; i++)
{
Console.Write("Type Number:");
string test = Console.ReadLine();
mylist.Add(test);
counter++;
}
string key = string.Join("", mylist); //note this key combination
//you will have key-value pair such as "12345"-5
Console.WriteLine(string.Join(",", mylist)); //note, you will print as "1,2,3,4,5"
dic.Add(key, counter);
And print it out like what has been shown:
foreach(var v in dic)
Console.WriteLine(v.Key.ToString() + " " + v.Value.ToString());
Original:
using foreach
on each Dictionary
element will do the job:
foreach(var v in dic)
Console.WriteLine(v.Key.ToString() + " " + v.Value.ToString());
The foreach
will allow you to iterate over every element in your Dictionary
.
Additionally, you may consider to reverse your Dictionary
key and value:
Dictionary<int, List<string>> dic = new Dictionary<int, List<string>>();
For it is quite uncommon to call int
from List<string>
. The Key
part of the Dictionary
is normally the simpler one. Also, by having a List<string>
as Key
, you have to have that exact List<string>
to call the Value
, but having int
as you Key
will allow you to get List<string>
from int
pretty easily.
And if you plan to join
the List<string>
you should use <string,int>
or <int,string>
rather than <List<string>,int>
or <int,List<string>>
Upvotes: 1
Reputation: 6375
Try this
foreach(var v in dic)
Console.WriteLine(string.Join("," v.Key) + " " + v.Value.ToString());
Although, it does seem like you have your key
and value
backwards...
Upvotes: 0