using System.Text.RegularExpressions;
using System.Collections.Generic;
static Dictionary<string, List<string>> dupDetection = new Dictionary<string, List<string>>();
static Dictionary<string, string> config = new Dictionary<string, string>
["ServiceBus__eng_topic_one__Listen"] = "Listen",
["ServiceBus__engtopicone__Listen"] = "Listen",
["ServiceBus__another_topic__Send"] = "Send",
["ServiceBus__anothertopic__Send"] = "Send",
["Cosmos__db_name__AccountName"] = "AccountName",
["Cosmos__dbname__AccountName"] = "AccountName",
["Cosmos__dbname__AccountKey"] = "AccountKey",
["Cosmos__db_name__AccountKey"] = "AccountKey",
["Unrelated-Config-Value"] = "ConfigValue"
public static void Main()
var finalConfig = new Dictionary<string, string>();
foreach (var key in config.Keys)
MatchCollection matchRegEx = Regex.Matches(key, "(ServiceBus|Cosmos)__([a-zA-Z0-9_]+)__(Listen|Send|AccountName|AccountKey)");
if (matchRegEx.Count > 0)
foreach (Match match in matchRegEx)
var keyName = match.Groups[2].Value;
var cleanedKey = key.Replace(keyName, keyName.Replace("_", ""));
if (!dupDetection.ContainsKey(cleanedKey))
dupDetection[cleanedKey] = new List<string>();
dupDetection[cleanedKey].Add(key);
finalConfig[key] = config[key];
foreach (var key in dupDetection.Keys)
var dupVal = dupDetection[key];
finalConfig[dupVal[0]] = config[dupVal[0]];
var chosenKey = dupVal.OrderBy(x => x).First();
if (config.ContainsKey(chosenKey))
var newKey = Regex.Replace(chosenKey, @"([^_])(_)([^_])", m => m.Groups[1].Value + "-" + m.Groups[3].Value);
finalConfig[newKey] = config[chosenKey];