I’m a rookie in programming and I have a problem understanding how to print elements from a List. In the task I’ve been given, I receive:
List<Dictionary<string,string>>() list = new List<Dictionary<string,string>>(); list.Add(processString(string, string)); list.Add(processString(string, string)); The processStrig is a Dictionary<string,string> and the keys are the same for both records.
I tried to create a new Dictionary and then populate it with foreach:
Dictionary<string,string>() dict = new Dictionary<string, string>(); foreach (Dictionary<string,string>r in list) { foreach (string inner in r.Keys) { if (!dict.ContainsKey(inner)) { dict.Add(inner, r[inner]); } } } and then print the new dict with another foreach, but it shows me only the first input because the keys are the same. So basically my question is how to print the both inputs? The output should look like this:
The output should look like this:
[0] "count":"some string" "order":"some string" [1] "count":"some other string" "order":"some other string"
list? If you are only printing for debugging purposes and don't care much about the format you could simply serialize to JSON and print that, e.g. viavar text = System.Text.Json.JsonSerializer.Serialize(list, new JsonSerializerOptions { WriteIndented = true });... Oh I see, the required format was shown in your original question without proper formatting. But why are you trying to add the inner dictionaries to some big outer dictionary? Why not just loop through the list, print a counter, then print each inner dictionary, using nestedforeachloops?Dictionary<TKEY,TVALUE>implements enumeration onKeyValuePair: useforeach (var entry in r) Console.WriteLine($"\"{entry.Key}\": \"{entry.Value}\"");processString(note: C# methods should have PascalCase names) twice, and it produces different results each time?