How can a dictionary be output in the form ?:

key1 val1 val2 val3 key2 val1 val2 val3 

Closed due to the fact that the essence of the question is incomprehensible by the participants: Igor , Andrew NOP , 0xdb , entithat , Suvitruf 29 Aug '18 at 10:11 .

Try to write more detailed questions. To get an answer, explain what exactly you see the problem, how to reproduce it, what you want to get as a result, etc. Give an example that clearly demonstrates the problem. If the question can be reformulated according to the rules set out in the certificate , edit it .

  • 3
    In Dictionary only one value can be associated with a single key. Maybe you need a Lookup , well, or use a list as a value in the dictionary. But most likely I did not understand the question. - Andrei NOP
  • Maybe you need to visit the site with the documentation? Doesn't the network have examples of Dictionary output code examples? - Vitaliy Shebanits

1 answer 1

Dictionary itself means storing data in the form Key = Value, where one Key contains only one Value . But, the benefit of Value, we can contain almost any object, which means that we can easily add collections to it.

Here is an example of the simplest dictionary with an array:

 Dictionary<string, string[]> dictionary = new Dictionary<string, string[]> { ["key1"] = new[] { "val1", "val2", "val3", }, ["key2"] = new[] { "val1", "val2", "val3", }, }; 

If you need to add something, then we can safely do the following:

 dictionary.Add("key3", new []{"val1", "val2"}); 

Changing values, the simplest:

 dictionary["key2"][0] = "val11"; 

Well, the conclusion of what you want:

 foreach (var item in dictionary) { Console.WriteLine($"{item.Key}"); foreach (var val in item.Value) { Console.WriteLine(" " + val); } } 

Well, or we can pervert and make a conclusion through LINQ:

 var result = dictionary.Aggregate(new StringBuilder(), (sb, kvp) => sb.AppendLine(kvp.Key).AppendLine(string.Join("\n", kvp.Value.Select(x => $" {x}"))), builder => builder.ToString()); Console.Write(result); 

Result:

 key1 val1 val2 val3 key2 val1 val2 val3 
  • I have a Dictionary <int, List <Obj >> (). And if I make ToDictionary (obj => obj.Property) for the collection (Simple List <Obj>) .. I will have a Dictionary <int, List <Obj> > ()? - arstan
  • one
    just in the piggy bank one more way var dictionary = new Dictionary<string, string[]>() { { "key1", new[] { "val1", "val2", "val3" } }, { "key2", new[] { "val1", "val2", "val3" } }, }; - tym32167
  • @arstan So you will get a Dictionary, where the key = Obj, and if there are two identical values ​​in List<Obj> , then you will get an error. It is better to group the original collection first, and only then translate it into a Dictionary, but this is another question ... - EvgeniyZ