I have a Dictionary<String,String> as follows
Dictionary<String, String> MyDict = new Dictionary<String, String>();
and which contains
MyDict.Add("A", "1010");
MyDict.Add("B", "1011");
MyDict.Add("C", "1110");
MyDict.Add("D", "1010");
MyDict.Add("E", "1011");
MyDict.Add("F", "1010");
I need to Compare the Dictionary Values and then to add the keys which all having same values
here is My resulting Dictionary
Dictionary<String, List<String>> MyResultDict = new Dictionary<String, List<String>>();
And My code
var XXX = MyDict.ToLookup(X => X.Value, X => X.Key);
MyResultDict = MyDict.ToDictionary(X => X.Key, X => XXX[X.Value].ToList());
The above code will produce the result like
{ "A" { "A" , "D", "F" } }
{ "B" { "B" , "E" } }
{ "C" { "C" } }
{ "D" { "A" , "D", "F" } }
{ "E" { "B" , "E" } }
{ "F" { "A" , "D", "F" } }
But my solution is having two problem
-
There exist Duplicate value list ( for the keys
D,EandF.) -
The Value List includes the key.
The Expected OutPut is like
{ "A" { "D", "F" } }
{ "B" { "E" } }
i.e There is no need of key C because C‘s value is not repeated anywhere.
and there is no need to include keys D , E and F because its already included in A‘s and B‘s value lists.
How to do this using Linq or Lambda Expression?
or possibly a bit simpler: