LINQ: Join operations on Hashtables / Dictionaries

In this example we will discuss, how to perform Join operation on dictionaries / hash tables. 
Consider 2 Dictionaries, one dictionary contains Roll No (Int) as key and a Structure (marks) (which contains marks of student) as value. Another dictionary contains Roll No(Int) as key and Name of Student (String) as value. Now we have to find name of students and corresponding marks of the students. 

So in this case we will perform Join on the key of both dictionaries and will have enumerable collection of KeyValue pairs (key will be name of student and value will have marks details) in the query result.

     var QueryResult = from mrks in stuResult.AsEnumerable<KeyValuePair<int, marks>>()
                       join pd in stuPDetails.AsEnumerable<KeyValuePair<int, string>>()
                       on mrks.Key equals pd.Key
                       select new KeyValuePair<String, marks>(pd.Value, mrks.Value);

Above mentioned LINQ query will perform join operation on the key values of the dictionaries. Finally selects the new KeyValue pairs having String(Name of Student) as key, marks(Marks details of the student) as value.

Example of JOIN on Dictionaries

public static Dictionary<int, marks> stuResult;
public static Dictionary<int,string> stuPDetails;
public struct marks
   {
      public int m_hindi;
      public int m_english;
      public int m_maths;
   }
   static void Main(string[] args)
   {
      stuResult = new Dictionary<int, marks>();
      stuPDetails = new Dictionary<int, string>();
      marks m = new marks();
      m.m_hindi = 47;
      m.m_english = 92;
     m.m_maths = 98;
     stuResult.Add(1, m);
     stuPDetails.Add(1, "Ramesh");
      m= new marks();
     m.m_hindi = 67;
     m.m_english = 87;
     m.m_maths = 96;
     stuResult.Add(2, m);
     stuPDetails.Add(2, "Suresh");
      m = new marks();
     m.m_hindi = 77;
     m.m_english = 72;
     m.m_maths = 64;
     stuResult.Add(3, m);
     stuPDetails.Add(3, "Mahesh");
      var QueryResult = from mrks in stuResult.AsEnumerable<KeyValuePair<int,marks>>()
                        join pd in stuPDetails.AsEnumerable<KeyValuePair<int, string>>()
                        on mrks.Key equals pd.Key
                        select new KeyValuePair<String, marks>(pd.Value, mrks.Value);
            foreach (KeyValuePair<string, marks>stud in QueryResult)
            {
              Console.WriteLine("Name:" + stud.Key);
                Console.WriteLine("English:" + stud.Value.m_english + "; Hindi:" + stud.Value.m_hindi + "; Maths:" + stud.Value.m_maths + "; Total:" + (stud.Value.m_hindi +
stud.Value.m_maths + stud.Value.m_english));
              Console.WriteLine("-----------------------------------------------");
            }

            Console.ReadLine();
        }

No comments:

Post a Comment