Where Clause with LINQ to Hashtable / Dictionaries

In this article, we will discuss How can we use where clause in LINQ to Object(Hastable / Dictionaries). Many time  while working with the Dictionaries or Hashtables, we may require to find out the values from them which satisfies some specific criteria. In that case we used to write iterations and then find the values which satisfies the criteria. Maybe writing the loop is a easy task for the beginners, but writing code for checking the values and performing the operations are so boring and tedious task.For the checking the values   for specific criteria we need to declare intermediate variables etc. But by using LINQ, this can be done so easily with few lines of code even without using iterations.

Consider, we have a Dictionary contains RollNo(Int) of Student, and value contains the structure's object having marks details of all the students. Now we have to find out the list of students got 80% or above marks So now our LINQ query will be like as


var QueryResult = from mrks in stuResult.AsEnumerable<KeyValuePair<int, marks>>()
                  where (mrks.Value.m_maths+mrks.Value.m_english+mrks.Value.m_hindi)/3 > 80
                  select mrks;

Sample Code

public static Dictionary<int,marks> stuResult;
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>();
          marks m = new marks();
         m.m_hindi = 47;
          m.m_english = 92;
          m.m_maths = 98;
         stuResult.Add(1, m);
          m = new marks();
          m.m_hindi = 67;
         m.m_english = 87;
         m.m_maths = 96;
         stuResult.Add(2, m);
         m = new marks();
         m.m_hindi = 77;
         m.m_english = 72;
         m.m_maths = 64;
         stuResult.Add(3, m);
          var QueryResult = from mrks in stuResult.AsEnumerable<KeyValuePair<int,marks>>()
           where (mrks.Value.m_maths + mrks.Value.m_english + mrks.Value.m_hindi) / 3 > 80
                            select mrks;
            foreach (KeyValuePair<int, marks> stud in QueryResult)
            {
               Console.WriteLine("RollNo:" + 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();
        }

output


1 comment:

  1. Where clause on the Key of the dictionary can be written as
    where mrks.Key = 2

    ReplyDelete