-17

This is a dictionary:

Dictionary<string, List<string>> Dic = new Dictionary<string, List<string>>();

I want to do the following: when I click a button the first dictionary (Dic) key and its values are copied to a list (List<string>). Click again, and the same thing happens, but this time with the next dictionary key and value.

Paul Fleming
  • 24,238
  • 8
  • 76
  • 113

2 Answers2

1

Looks like you want to create a new List<string> based on your all string elements in the dictionary's List values. You may use SelectMany to flatten it out and get a list using the following code:

Dictionary<string, List<string>> Dic = new Dictionary<string, List<string>>();
Dic.Add("1", new List<string>{"ABC","DEF","GHI"});
Dic.Add("2", new List<string>{"JKL","MNO","PQR"});
Dic.Add("3", new List<string>{"STU","VWX","YZ"});

List<string> strList = Dic.SelectMany(r => r.Value).ToList();

Where strList will contain all the string items from the dictionary in a single list.

Habib
  • 219,104
  • 29
  • 407
  • 436
0

why not use ToList method?

Dictionary<string, int> dictionary = new Dictionary<string, int>();
dictionary["cat"] = 1;
dictionary["dog"] = 4;
dictionary["mouse"] = 2;
dictionary["rabbit"] = -1;

// Call ToList.
List<KeyValuePair<string, int>> list = dictionary.ToList();

// Loop over list.
foreach (KeyValuePair<string, int> pair in list)
{
    Console.WriteLine(pair.Key);
    Console.WriteLine("   {0}", pair.Value);
}
John Woo
  • 258,903
  • 69
  • 498
  • 492