Skip to content

Instantly share code, notes, and snippets.

@jianminchen
Created April 20, 2017 18:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jianminchen/c0004cb428d8c5e8624d2df6ddefa7d5 to your computer and use it in GitHub Desktop.
Save jianminchen/c0004cb428d8c5e8624d2df6ddefa7d5 to your computer and use it in GitHub Desktop.
recursive talk - dictionary - make it compile - learn to check type using "is string", and type casting in the code writing process
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace FlatDictionary_MockingExperience
{
// Flat a ctionary
// key: string
// value is string, sometimes it is dictionary
// value '1' - string
// 'a': '2' key 'a' value string '2'
// 'c': key, value is Dictionary
// key1: 1
// value, how can I determine that it is a string or dictionary
// Key2.a: '2'
// key2.b: '3'
// key is constructed by concatenated key2 -> DFS -> recursive function
// keystring prefix = empty string
// create new Dictionary <string, string>
// step 1: Dictionary -> keys -> iterate on the key
// step 2: for each key, value object -> Determine Runtime type -> string , Dictionary
// step 3: output the key value pair to new dictionary -> key, value is the same
// step 4: if value is Dictinary, continue step 1 -> pass into key string prefix
// return new dictionary <string, string>
class LearningExperience {
static void Main(string[] args) {
Console.WriteLine("Meet a talent and talk about algorithm");
var data = new Dictionary<string, object>();
data.Add("key1","1");
var data2 = new Dictionary<string, object>();
data.Add("key2","3");
data.Add("key2", data2);
var flatten = new Dictionary<string, object>();
FlattenDictionary(data, flatten, string.Empty);
}
/// key1: 1
/// DFS -> overflow -> too deep -> iterative solution out-of-stack
//
public static void FlattenDictionary(Dictionary<string, object> data, Dictionary<string, object> flatten, string prefix)
{
if(data == null || data.Count == 0) return;
foreach(string key in data.Keys)
{
var current = data[key];
var newKey = (prefix == null)? key : (prefix +'.' +key) ;
if(current is string)
{
flatten.Add(newKey, current);
}
else
{
// it is a dictionary
prefix = newKey; // Key2
FlattenDictionary((Dictionary<string, object>)current, flatten, prefix);
}
}
// do nothing
return;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment