Anonymous Types & Implicitly Typed Variables:

While writing LINQ queries, there might be situation to return information from several classes. However, when you retrieve information from different class sources in this manner, you cannot retrieve a generic list of your class type because you are not retrieving a specific class type. This is where Anonymous Types step in and make things easier because Anonymous Types allow you to create a class structure on the fly.

When you create an Anonymous Type you need to declare a variable to refer to the object. Since you do not know what type you will be getting (since it is a new and anonymous type), you can declare the variable with the var keyword. This technique is called using an Implicitly Typed Variable.

When writing a LINQ query expression, you may return various pieces of information. You could return all of these data bits and create an Anonymous Type to store them. For example, let’s assume you have a List and each Customer has a BusinessAddress property of type Address. In this situation you want to return the CompanyName and the State where the company is located.

Extension Methods:

This new C# 3.0 feature enables us to add new static methods to existing types with out touching the source files of those types. As per the code we can declare extension methods as

  • Declare the static class to hold those methods.
  • Add the method definition, while declaration add ‘this’ keyword before which are adding this extension method. i.e. for ex: Add, we added this before int, this means we added this method on int types.
  • In the first two methods, we need to pass one parameter, whereas for the third method no need to pass parameter as this syntax is used to show that this method is invoked on ‘int’ types.

public static  class Methods

    {

        public static int Add(this int a, int b)

        {

            return a + b;

        }

        public static int DoubleTheSum(this int a, int b)

        {

            return(( a.Add(b))*(a.Add(b)));

        }

        public static int Negate(this int a)

        {

            return (-a);

        }

    }

  

    class Program

    {     

        static void Main(string[] args)

        {

            int a = 1;

            int b = 9;

            int c=a.Add(b);

            Console.WriteLine(“Sum : “ + c);

            Console.WriteLine(“Double of Sum : “ + a.DoubleTheSum(b));

            Console.WriteLine(“Negation of a is: “ + a.Negate());

            Console.ReadLine();           

           

        }      

    }

 

Object & Collection Initializers :

Object Initializers: C # 3.0 new features which allow direct named initialization of public variables of a class with out need of constructors.This is a great feature as it removes the need to create multiple overloaded constructors using different parameter lists to achieve the same goal. While you can currently create your own constructors, Object initializers are nice because you do not have to create multiple overloaded constructors to handle the various combinations of how you might want to initialize the


class Student

    {

        public int RollNo;

        public string StuName;

        public float Total;

    }

  

    class Program

    {

        static void Main(string[] args)

        {

            Student s1 = new Student { RollNo = 21, StuName = “shalini

            p”, Total = 83.63 };

        }      

    }

 

Collection Initializers: Prior to C# 3.0, it’s not allowed to initialize the collection of objects during initialization itself, i.e. First need to initialize and then need to add objects to the collection variables.

But with this Collection Initialisers, we can initialize the list of objects as


 

    class Student

    {

        public int RollNo;

        public string StuName;

        public float Total;

    }

  

    class Program

    {

        static void Main(string[] args)

        {

            List<Student> sList = new List<Student> { new Student {

            RollNo = 1, StuName = “shalini”, Total = 83 }, new Student

            { RollNo = 2, StuName = “pratyusha”, Total = 82 } };

 

        }      

    }

 

Anonymous Properties:

This is the new feature introduced in C# 3.0

Prior to C# 3.0, we have properties declared as below.

 

  class Test

    {

        private string MyName;

        public string Name

        {

            get

            {

                return MyName;

            }

            set

            {

                MyName = value;

            }

        }

    }

 There is no much logic inside the properties getters and setters; these are made short in C# by name Anonymous Properties as

   class Test

    {

        public string MyName { get; set; }

       

    }

 

Using Properties, we can restrict variable properties like ‘Read-Only (only getter)’, ‘Write only’ (Only setter). Read Write (Both getter & Setter).

I.e. Prior to C# 3.0, we can include either get or set or both.

But Anonymous Properties as a new feature in C# 3.0, we need to include both get and set while declaring the properties. But we can achieve the ‘Read-Only’ by declaring as

  class Test

    {

        public string MyName { get;private set; }

       

    }

||’ly we can achieve ‘Write Only’ property by declaring as

    class Test

    {

        public string MyName { private get; set; }

       

    }

If the property has both getter & setter of public type, one can think why to go for properties instead of public variables.

Here is a lay down of differences between variables & properties:

  • Variables have single line of declaration & single of piece of memory allocated for them. Whereas for properties, there are series of declarative statements and memory will be allocated for the whole block.
  • Custom manipulations cannot be done with variables, whereas properties can be done using setters and getters.
  • Unlike a variable, the value of a property might not correspond directly to a single item of storage. The storage might be split into pieces for convenience or security, or the value might be stored in an encrypted form. In these cases the Get procedure would assemble the pieces or decrypt the stored value, and the Set procedure would encrypt the new value or split it into the constituent storage. A property value might be ephemeral, like time of day, in which case the Get procedure would calculate it on the fly each time you access the property.

 

Grouping Operators in Linq:

Let’s explore the various Grouping operations in Linq using ‘group by’ in both Query syntax & Method Syntax Format with the help of following program.

The Employee & Department are the Classes created for the demo purpose.


public class Employee

   {

      public int EmpNo;

      public string EmpName;

      public float salary;

      public int DeptNo;

      public int[] Reportees;//list of the emp-id’s of reportees

      public Employee(int eno, string Ename, float sal, int No,int[] r)

       {

            EmpNo = eno; EmpName = Ename; salary = sal; DeptNo = DNo;

            Reportees = r;

       }

    }

 

    public class Department

    {

        public int DeptNo;

        public string DeptName;

        public Department(int dno, string dname)

        {

            DeptNo = dno;DeptName = dname;

        }

    }

 


static void Main(string[] args)

        {          

            List<Department> dList = new List<Department>();

            dList.Add(new Department(1, “Tech Lead”));

            dList.Add(new Department(2, “Project Lead”));

            dList.Add(new Department(3, “Module Lead”));

            List<Employee> EmpList = new List<Employee>();

            EmpList.Add(new Employee(1, “ppp”, 100, 1, new

            int[]{2,3,4,5,6}));

            EmpList.Add(new Employee(2, “qqq”, 70, 2, new

            int[]{3,4,5,6}));

            EmpList.Add(new Employee(3, “rrr”, 50, 3, new

            int[]{4,5,6}));

            EmpList.Add(new Employee(4, “xxx”, 100, 1, new

            int[]{5,6}));

            EmpList.Add(new Employee(5, “yyy”, 100, 1, new int[]{6}));

            EmpList.Add(new Employee(6, “zzz”, 50, 3, new int[]{}));

            // different queries of type – Grouping

            // In the Query syntax & method syntax

            //1. Simple Group by

            var q1 = from e1 in EmpList

                     group e1 by e1.DeptNo;

            q1 = EmpList.GroupBy(e1 => e1.DeptNo);

 

            var q2 = from e1 in EmpList

                      group e1 by e1.DeptNo into g

                      select new { DeptNo = g.Key, Emp = g };

            q2 = EmpList.GroupBy(e1 => e1.DeptNo).Select(g => new

                 {DeptNo=g.Key,Emp=g });

 

            //2. Simple Group by & ordering the resulted groups on

            // deptno basis

            var q3 = from e1 in EmpList

                     group e1 by e1.DeptNo into g

                     orderby g.Key

                     select g;

            q3 = EmpList.GroupBy(e1 => e1.DeptNo).OrderBy(g => g.Key);

 

            //3.selecting only few coloumns from the grouped data

            var q4 = from e1 in EmpList

                     group e1 by e1.DeptNo into g

                     select new { count = g.Count(), deptNo = g.Key };

            q4 = EmpList.GroupBy(e1 => e1.DeptNo).Select(g => new {

                 count = g.Count(), deptNo = g.Key });

     

 

            //4.Filtering the data before grouping

            var q5 = from e1 in EmpList

                     where e1.EmpNo < 6

                     group e1 by e1.DeptNo into g

                     select g;

            q5 = EmpList.Where(e1 => e1.EmpNo < 6).GroupBy(e1 =>

                 e1.DeptNo);

 

            //5.Filtering the groups (after grouping)

            var q6 = from e1 in EmpList

                     group e1 by e1.DeptNo into g

                     where g.Key==1

                     select new {Deptno=g.Key,Count=g.Count()};

            q6 = EmpList.GroupBy(e1 => e1.DeptNo).Where(g => g.Key ==

                 1).Select(g => new { Deptno = g.Key, Count = g.Count()

                 });

 

            //6.Group By Multiple values

            var q7 = from e1 in EmpList

                     group e1 by (new { e1.EmpName, e1.DeptNo }) into g

                     select

            new{Dno=g.Key.DeptNo,Ename=g.Key.EmpName,count=g.Count()};              

        }

 

Ordering Operators :

We use order by operator to display the objects in the sorted order. Default sorting order is ‘ascending’. If we want to sort in descending order, we can mention it explicitly.

The Employee & Department are the Classes created for the demo purpose.

public class Employee

   {

      public int EmpNo;

      public string EmpName;

      public float salary;

      public int DeptNo;

      public int[] Reportees;//list of the emp-id’s of reportees

      public Employee(int eno, string Ename, float sal, int No,int[] r)

       {

            EmpNo = eno; EmpName = Ename; salary = sal; DeptNo = DNo;

            Reportees = r;

       }

    }

 

    public class Department

    {

        public int DeptNo;

        public string DeptName;

        public Department(int dno, string dname)

        {

            DeptNo = dno;DeptName = dname;

        }

    }

 

static void Main(string[] args)

        {          

            List<Department> dList = new List<Department>();

            dList.Add(new Department(1, “Tech Lead”));

            dList.Add(new Department(2, “Project Lead”));

            dList.Add(new Department(3, “Module Lead”));

            List<Employee> EmpList = new List<Employee>();

            EmpList.Add(new Employee(1, “ppp”, 100, 1, new

            int[]{2,3,4,5,6}));

            EmpList.Add(new Employee(2, “qqq”, 70, 2, new

            int[]{3,4,5,6}));

            EmpList.Add(new Employee(3, “rrr”, 50, 3, new

            int[]{4,5,6}));

            EmpList.Add(new Employee(4, “xxx”, 100, 1, new

            int[]{5,6}));

            EmpList.Add(new Employee(5, “yyy”, 100, 1, new int[]{6}));

            EmpList.Add(new Employee(6, “zzz”, 50, 3, new int[]{}));

            // different queries of type – ordering

            // In the Query syntax & method syntax

            //1.Order By – ordering by one field in ascending order

            var q1 = from e1 in EmpList

                     orderby e1.EmpName

                     select e1;

            q1 = EmpList.OrderBy(e1 => e1.EmpName);

 

            //2.Order By – ordering by one field in descending order

            var q2 = from e1 in EmpList

                     orderby e1.EmpName descending

                     select e1;

            q2 = EmpList.OrderByDescending(e1 => e1.EmpName);

 

 

            //3.Order By – ordering by two field in ascending order

            var q3 = from e1 in EmpList

                     orderby e1.DeptNo, e1.EmpName

                     select e1;

            q3 = EmpList.OrderBy(e1 => e1.DeptNo).ThenBy(e1 =>

                 e1.EmpName);

 

 

            //4.Order By – ordering by two field in descending order

            var q4 = from e1 in EmpList

                     orderby e1.DeptNo, e1.EmpName

                     select e1;

            q4 = EmpList.OrderByDescending(e1 =>

                 e1.DeptNo).ThenByDescending(e1 => e1.EmpName);

 

            //5.Reverse

            var q5 = (from e1 in EmpList

                      select e1).Reverse();

                  

        }

About ‘ThenBy’ keyword:

ThenBy is one of the ordering query operators available in linq. We can use ThenBy operator with linq to objects, linq to XML and linq to SQL. We use ThenBy operator to do secondary sort when writing queries in  method syntax. ThenBy operator is used to sort by more than 1 property. When we want to sort initially we would start with using the orderby operator. Since orderby operator returns IOrderderedEnumerable<T>,we cannot reuse the orderby operator again because it can be only used on sequences that implement IEnumerable<T>.  This is where the ThenBy operator comes into play. ThenBy operator is an extension method that is available on input sequence that implement IOrderededEnumerable<T> and also returns IOrderedEnumerable<T> which allows you to reuse it multiple times if you want to sort by more than 1 column or property. 

Partitioning Operators in Linq:

Lets explore the various partitioning operations in Linq using Take, TakeWhile, Skip, SkipWhile in both Query syntax & Method Syntax Format with the help of following program.

The Employee & Department are the Classes created for the demo purpose.


public class Employee

   {

      public int EmpNo;

      public string EmpName;

      public float salary;

      public int DeptNo;

      public int[] Reportees;//list of the emp-id’s of reportees

      public Employee(int eno, string Ename, float sal, int No,int[] r)

       {

            EmpNo = eno; EmpName = Ename; salary = sal; DeptNo = DNo;

            Reportees = r;

       }

    }

 

    public class Department

    {

        public int DeptNo;

        public string DeptName;

        public Department(int dno, string dname)

        {

            DeptNo = dno;DeptName = dname;

        }

    }

 


static void Main(string[] args)

        {          

            List<Department> dList = new List<Department>();

            dList.Add(new Department(1, “Tech Lead”));

            dList.Add(new Department(2, “Project Lead”));

            dList.Add(new Department(3, “Module Lead”));

            List<Employee> EmpList = new List<Employee>();

            EmpList.Add(new Employee(1, “ppp”, 100, 1, new

            int[]{2,3,4,5,6}));

            EmpList.Add(new Employee(2, “qqq”, 70, 2, new

            int[]{3,4,5,6}));

            EmpList.Add(new Employee(3, “rrr”, 50, 3, new

            int[]{4,5,6}));

            EmpList.Add(new Employee(4, “xxx”, 100, 1, new

            int[]{5,6}));

            EmpList.Add(new Employee(5, “yyy”, 100, 1, new int[]{6}));

            EmpList.Add(new Employee(6, “zzz”, 50, 3, new int[]{}));

            // different queries of type – Partitioning

            // In the Query syntax & method syntax

            //Take

            //1.Collecting first 2 employee’s objects

            var q1 = (from e1 in EmpList

                      select e1).Take(2);

             q1 = EmpList.Take(2);

           

            //2.Collecting first 2 employee’s of department id=1

            var q2 =(from e1 in EmpList

                     where e1.DeptNo == 1

                     select e1).Take(2);           

             q2 = EmpList.Where(e1 =&gt; e1.DeptNo = 1).Take(2);

 

            //Skip

            //3.Collects all but first 2 employee’s

             var q3 =( from e1 in EmpList

                      select e1).Skip(2);

             q3 = EmpList.Skip(2);

 

            //4.Skips first record of employee whose department id=1

             var q4 =(from e1 in EmpList

                      where e1.DeptNo == 1

                      select e1).Skip(1);

             q4 = EmpList.Where(e1 =>e1.DeptNo = 1).Skip(1);

 

 

            //5.TakeWhile-used to take records from starting to the

            //point where condition on an object is hit

            //collects all the records untill employee name becomes

            //’xxx’

            var q5 = (from e1 in EmpList

                      select e1).TakeWhile(e1=>e1.EmpName!=“xxx”);

            q5 = EmpList.TakeWhile(e1 =>e1.EmpName != “xxx”);

 

            //6.SkipWhile-used to Skip records from starting to the

            // point where condition on an object is hit

            //Skips all the records untill employee name becomes ‘xxx’

             var q6 = (from e1 in EmpList

                      select e1).SkipWhile(e1=>e1.EmpName!=“xxx”);

             q6 = EmpList.SkipWhile(e1 => e1.EmpName != “xxx”);

                  

        }

 

 

 

 

Restriction Operators :

Lets explore the various Restriction operations in Linq using ‘where’ in both Query syntax & Method Syntax Format with the help of following program.

The Employee & Department are the Classes created for the demo purpose.


public class Employee

   {

      public int EmpNo;

      public string EmpName;

      public float salary;

      public int DeptNo;

      public int[] Reportees;//list of the emp-id’s of reportees

      public Employee(int eno, string Ename, float sal, int No,int[] r)

       {

            EmpNo = eno; EmpName = Ename; salary = sal; DeptNo = DNo;

            Reportees = r;

       }

    }

 

    public class Department

    {

        public int DeptNo;

        public string DeptName;

        public Department(int dno, string dname)

        {

            DeptNo = dno;DeptName = dname;

        }

    }

 


static void Main(string[] args)

        {          

            List<Department> dList = new List<Department>();

            dList.Add(new Department(1, “Tech Lead”));

            dList.Add(new Department(2, “Project Lead”));

            dList.Add(new Department(3, “Module Lead”));

            List<Employee> EmpList = new List<Employee>();

            EmpList.Add(new Employee(1, “ppp”, 100, 1, new

            int[]{2,3,4,5,6}));

            EmpList.Add(new Employee(2, “qqq”, 70, 2, new

            int[]{3,4,5,6}));

            EmpList.Add(new Employee(3, “rrr”, 50, 3, new

            int[]{4,5,6}));

            EmpList.Add(new Employee(4, “xxx”, 100, 1, new

            int[]{5,6}));

            EmpList.Add(new Employee(5, “yyy”, 100, 1, new int[]{6}));

            EmpList.Add(new Employee(6, “zzz”, 50, 3, new int[]{}));

          // different queries of type – Restriction

          // In the Query syntax & method syntax

          //1.Filtering based on DeptNo

            var q1 = from e1 in EmpList

                     where e1.DeptNo==1

                     select e1;

            q1=EmpList.Where(e1=>e1.DeptNo==1).Select(e1=>e1);

          //2.Filtering the Employees whose name starts with ‘p’

            var q2 = from e1 in EmpList

                     where e1.EmpName.StartsWith(“p”)

                     select e1;

            q2=EmpList.Where(e1=>e1.EmpName.StartsWith(“p”));

 

          //3.Index in where condition

            var q3 = EmpList.Where((e1, i) => e1.EmpName.Length ==

                     i);                      

 

        }

 

 

Projection Operators in Linq:

Lets explore the various projection operations in Linq using ‘select’ & ‘selectmany’ in both Query syntax & Method Syntax Format with the help of following program.

The Employee & Department are the Classes created for the demo purpose.


public class Employee

   {

      public int EmpNo;

      public string EmpName;

      public float salary;

      public int DeptNo;

      public int[] Reportees;//list of the emp-id’s of reportees

      public Employee(int eno, string Ename, float sal, int No,int[] r)

       {

            EmpNo = eno; EmpName = Ename; salary = sal; DeptNo = DNo;

            Reportees = r;

       }

    }

 

    public class Department

    {

        public int DeptNo;

        public string DeptName;

        public Department(int dno, string dname)

        {

            DeptNo = dno;DeptName = dname;

        }

    }

 


static void Main(string[] args)

       {          

            List<Department> dList = new List<Department>();

            dList.Add(new Department(1, “Tech Lead”));

            dList.Add(new Department(2, “Project Lead”));

            dList.Add(new Department(3, “Module Lead”));

            List<Employee> EmpList = new List<Employee>();

            EmpList.Add(new Employee(1, “ppp”, 100, 1, new

            int[]{2,3,4,5,6}));

            EmpList.Add(new Employee(2, “qqq”, 70, 2, new

            int[]{3,4,5,6}));

            EmpList.Add(new Employee(3, “rrr”, 50, 3, new

            int[]{4,5,6}));

            EmpList.Add(new Employee(4, “xxx”, 100, 1, new

            int[]{5,6}));

            EmpList.Add(new Employee(5, “yyy”, 100, 1, new int[]{6}));

            EmpList.Add(new Employee(6, “zzz”, 50, 3, new int[]{}));

          // different queries of type – Projection

          // In the Query syntax & method syntax

          //1.selecting all the list of employee objects

            var q1 = from e1 in EmpList

                     select e1;

            q1 = EmpList.Select(e1=>e1);           

 

          //2.selecting only required field from Employee list

          //objects

            var q2 = from e1 in EmpList

                     select e1.EmpNo;

            q2 = EmpList.Select(e1 => e1.EmpNo);

 

          //3.Select – transformation Data- selecting all the yearly

          //salaries of all employees

            var q3 = from e1 in EmpList

                     select e1.salary * 12;

            q3 = EmpList.Select(e1 => e1.salary * 12);

 

          //4.Select – Anonymous types

            var q4 = from e1 in EmpList

                     select new { EmployeeNo = e1.EmpNo, AnnuualSalary

                     = e1.salary * 12 };

            q4 = EmpList.Select(e1 => new { EmployeeNo = e1.EmpNo,

                 AnnuualSalary = e1.salary * 12 });

 

 

          //5.Select – Anonymous types

            var q5 = from e1 in EmpList

                     join d1 in dList on e1.DeptNo equals d1.DeptNo

                     select new { EmployeeNo = e1.EmpNo,

                     DepartmentName=d1.DeptName };           

 

          //6.Select – Indexed

          //checking whether employee object index = employee id

            var q6=EmpList.Select((e1, index) => new { Num = e1.EmpNo,

                   InPlace = (e1.EmpNo == index) });

 

          //7.Select – Collection from more than one list

          //collects lists from both the lists ie..picks each value in

          //1st list & evaluates against all values in the 2nd list

            var q7 = from e1 in EmpList

                     from d1 in dList

                     where e1.DeptNo == d1.DeptNo

                     select new {e1.EmpNo,d1.DeptName };           

           

          //8.Select – querying the inner object

          //selecting all the reportees of all the employee’s

            var q8 = from e1 in EmpList

                     from r in e1.Reportees

                     select new {ManagerName=e1.EmpName,ReporteeId=r };

            q8 = EmpList.SelectMany(e1 => e1.Reportees.Select(r => new

                 {ManagerName=e1.EmpName,ReporteeId=r }));

 

          //9.Select – querying the inner object with a condition

          //selecting all the managers for the reportee id=2

            var q9 = from e1 in EmpList

                     from r in e1.Reportees

                     where r==2

                     select new { ManagerName = e1.EmpName, ReporteeId

                     = r };

            q9 = EmpList.SelectMany(e1 => e1.Reportees.Where(r => r ==

                 2).Select(r => new { ManagerName = e1.EmpName,

                 ReporteeId = r }));

 

          //10.Filtering on the outer as well inner object

          //selecting the managers of the reportee with id=6 & mangers

          //who are from deptid=1,2

            var q10 = from e1 in EmpList

                      where e1.DeptNo==1 || e1.DeptNo==2

                      from r in e1.Reportees

                      where r == 6

                      select new { ManagerName = e1.EmpName, ReporteeId

                      = r };

            q10 = EmpList.Where(e => e.DeptNo == 1 || e.DeptNo ==

                  2).SelectMany(e1 => e1.Reportees.Where(r => r ==

                  6).Select(r => new { ManagerName = e1.EmpName,

                  ReporteeId = r }));

 

           

          //11.SelectMany

            var q11 = EmpList.SelectMany((e1, i) =>

                      e1.Reportees.Select(r => i+1 + “)employee Name :”

                      + e1.EmpName + ” has reportee with id =” + r));

                      q11 = EmpList.SelectMany(e1 =>

                      e1.Reportees.Select(r => r.ToString()));

          //12.Selecting the First result object out of selected

          //collection

            var q12 = (from e1 in EmpList

                       select e1.EmpName).FirstOrDefault();

                      

 

        }