Custom / Partial Projection in LINQ to Hashtable / Dictionary

Like SQL we can project partial or custom data in output. In the output of LINQ Query it will be an enumerable collection of anonymous type. This anonymous type is being created by using new operator in the select clause and member fields are generated dynamically in the select new part of the LINQ.

Consider a data dictionary and structure as followed:
public static Dictionary<int, marks> stuResult;
public struct marks
{
   public int m_hindi;
   public int m_english;
   public int m_maths;
}

Consider marks is structure datatype which contains marks details of a student. stuResult Dictionary contains RollNo(int), as key and object of marks as its value. Now we have to find out the Total marks obtained by each students. To find this LINQ will be as:


var QueryResult = from mrks in stuResult.AsEnumerable<KeyValuePair<int, marks>>()
                  select new
                  {
                   Total = mrks.Value.m_hindi + mrks.Value.m_english + mrks.Value.m_maths,
                   RollNo = mrks.Key
                  };

Here the QueryResult is an Enumerable Collection of anonymous type, which has to data members which are Total & RollNo. These can be iterated as followed

foreach (var stud in QueryResult)
        {
            Console.WriteLine("RollNo:" + stud.RollNo);
            Console.WriteLine("Total:" + stud.Total);
            Console.WriteLine("-----------------------------------------------");
        }

No comments:

Post a Comment