I'm trying to produce a list of string Key combinations when each Key shares a value, below is an extract from my code
var keyCombos = new List<List<string>>();
var dict = new Dictionary<string, List<int>>();
dict.Add("A", new List<int>() { 1, 2, 3 });
dict.Add("B", new List<int>() { 1, 2, 3, 4 });
dict.Add("C", new List<int>() { 1, 4, 5 });
Above is a Dictionary which contains a string Key and an integer list as its value, the keyCombos
list will hold all Key combinations for shared integer list values, my expected output for keyCombos
would be below
["A","B","C"] //1 is common
["A","B"] //1,2,3 are common
["B","C"] //1,4 are common
["C"] //5
The order of the combinations is not important, so far with my code using various foreach
loops I can only combinations of 2 Keys, not 1 or 3.
foreach(var k1 in dict.Keys)
{
List<int> a1 = dict[k1];
foreach (var k2 in dict.Keys)
{
if (k1 != k2)
{
List<int> a2 = dict[k2];
if(a1.Intersect(a2).Count()>0)
{
var matches = false;
foreach(var combo in keyCombos)
{
if ((combo.Contains(k1)) && (combo.Contains(k2)))
{
matches = true;
}
}
if (!matches)
{
keyCombos.Add(new List<string>() { k1, k2 });
}
}
else
{
keyCombos.Add(new List<string>() { k1 });
}
}
}
}