Wednesday, March 5, 2014

Accessing values inside nested dictionaries without using FOR loop in C#

consider the following example

In the code below, find the method 'AlphabetList' in the class 'QnTwo'. There will be a list of dictionary named ‘dictList’. Using a single linq query, extract from 'dictList' a list of string that would contain all the alphabets in 'dict1', 'dict2' and 'dict3'. Do not iterate (using for, foreach etc) any of the lists or dictionaries for extracting the answer.
 public void AlphabetList()
        {
            Dictionary<intList<string>> dict1 = new Dictionary<intList<string>>();
            dict1.Add(1, new List<string>() { "a""b""c" });
            dict1.Add(2, new List<string>() { "d""e""f" });

            Dictionary<intList<string>> dict2 = new Dictionary<intList<string>>();
            dict2.Add(3, new List<string>() { "g""h""i" });
            dict2.Add(4, new List<string>() { "j""k""l" });
            dict2.Add(5, new List<string>() { "m""n""o" });

            Dictionary<intList<string>> dict3 = new Dictionary<intList<string>>();
            dict3.Add(6, new List<string>() { "p""q""r" });
            dict3.Add(7, new List<string>() { "s""t""u" });

            //put the tuples into a collection
            List<Dictionary<intList<string>>> dictList = new List<Dictionary<intList<string>>>();
            dictList.Add(dict1);
            dictList.Add(dict2);
            dictList.Add(dict3);
        }



The solution here is to use LINQ

                var s = dictList.SelectMany(x => x.SelectMany(y => y.Value));