Kian
Kian

Reputation: 11

Permutations on Dictionary in C#

I have a dictionary filled with keys and values. I am trying to get all possible combinations of the keys without duplicates. So AB and BC and CDE but not BA. The values are not important at this time, later I will make use of them. How do I go about doing this?

Dictionary<string, int> datadict = new Dictionary<string, int>();

datadict.Add("A", 310);
datadict.Add("B", 200);
datadict.Add("C", 510);
datadict.Add("D", 340);
datadict.Add("E", 230);
datadict.Add("F", 940);
datadict.Add("G", 470);
datadict.Add("H", 430);
datadict.Add("I", 440);
datadict.Add("J", 360);

Upvotes: 0

Views: 550

Answers (1)

Kavindu Dodanduwa
Kavindu Dodanduwa

Reputation: 13059

It is possible with some LINQ and for-loops

Extracting Key set as an array using LINQ

var KeyList = datadict.Select(r => r.Key).ToArray();

Sample program : Combinations of 2 characters

// Keys are extracted from Dictionary : A String Array
var KeyList = datadict.Select(r => r.Key).ToArray();
// Values are extracted from Dictionary : An int Array
var ValueList = datadict.Select(r => r.Value).ToArray();

// Here I have provided a simple algorithm to get Combinations of Two characters
// Ex : AB , AC ... 
// Does not get AA. BB .. OR BA, CA..

int res=0;
// Outer Loop walk through all elements
for (int i = 0; i < KeyList.Length; i++)
{
     // Inner loop walk from outer loop index +1 
     for (int j = i+1; j < KeyList.Length; j++)
     {
          // Find the SUM 
          res=ValueList[i]+ValueList[j];

          // Permutations and the SUM
          Console.WriteLine(KeyList[i]+KeyList[j]+"  "+res);
     }
}

Output :

AB
AC
AD
.
.
IJ

Upvotes: 1

Related Questions