-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.

5
  • Sorry I don't understand your question. Do you mean you want to add a list to a Dictionary? Or are you having problems with accessing the List<string>?
    – hydev
    Sep 7, 2012 at 6:54
  • There is no definite order in Dictionary.
    – mbm
    Sep 7, 2012 at 6:54
  • What about your previous question
    – Habib
    Sep 7, 2012 at 6:55
  • Hydev, no ) I want copy elements from Dictionary to List Sep 7, 2012 at 6:57
  • helping you would be much simpler if you add an example with the content of the dictionary and the contento of the list after each click... Sep 7, 2012 at 8:03

2 Answers 2

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.

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);
}
1
  • i have Dictionary<string, List<string>> Dic = new Dictionary<string, List<string>>();------------------ no Dictionary<string, int> dictionary = new Dictionary<string, int>(); Sep 7, 2012 at 6:59

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.