Skip to content

Instantly share code, notes, and snippets.

@jianminchen
Created June 21, 2017 04:59
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/81d248f0999acc476540ce218c819644 to your computer and use it in GitHub Desktop.
Save jianminchen/81d248f0999acc476540ce218c819644 to your computer and use it in GitHub Desktop.
Dictionary - recursive function - depth first search
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace flattenDictionary
{
/// <summary>
/// Flatten dictionary - recursive function practice
/// </summary>
class Program
{
static Dictionary<string, object> flattenDictionary(Dictionary<string, object> dict)
{
// your code goes here
flatten.Clear();
flattenDictionaryHelper(dict, "");
return flatten;
}
public static Dictionary<string, object> flatten = new Dictionary<string, object>();
/// <summary>
///
/// </summary>
/// <param name="dict"></param>
/// <param name="prefix"></param>
public static void flattenDictionaryHelper(Dictionary<string, object> dict, string prefix)
{
if (dict == null)
{
return;
}
foreach (var pair in dict)
{
var key = pair.Key;
var value = pair.Value;
bool isDictionaryTrue = isDictionary(value);
// added after mocking, reset for every pair. Bug found in mocking test
var nextPrefix = prefix;
nextPrefix += (prefix.Length > 0) ? "." : "";
nextPrefix += key;
if (isDictionaryTrue)
{
flattenDictionaryHelper((Dictionary<string, object>)value, nextPrefix);
}
else
{
flatten.Add(nextPrefix, value); // prefix includes key
}
}
}
// Check Object type in C#
// https://stackoverflow.com/questions/3561202/check-if-instance-of-a-type
private static bool isDictionary(Object value)
{
return value.GetType() == typeof(Dictionary<string, object>);
}
static void Main(string[] args)
{
var dictionary =
new Dictionary<string, Object>();
dictionary.Add("Key1", "1");
var subDict1 =
new Dictionary<string, Object>();
subDict1.Add("a", "2");
subDict1.Add("b", "3");
var subDict2 =
new Dictionary<string, Object>();
subDict2.Add("d", "2");
subDict2.Add("e", "3");
subDict1.Add("c", subDict2);
dictionary.Add("Key2", subDict1);
var flatten = flattenDictionary(dictionary);
foreach (var kvp in flatten)
{
Console.WriteLine("Key = {0}, Value = {1}", kvp.Key, kvp.Value);
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment