LINQ – Extension Methods in Csharp and LINQ Operators

Extension methods allow us to add methods to existing types without creating a new derived type, recompiling, or otherwise modifying the original type. we may say that if the source code for the class is unavailable or if we don’t have authorization to make modifications to the class, we can utilize the Extension methods as a technique to extend the functionality of the class in the future by adding new methods.

When should you utilise Extension Methods in C#?

  • You require a method on an existing type, but you do not possess the source code for that type.
  • You require a method on an existing type, and while you control the source code for that type, it is an interface.
  • You require a method on an existing type; you own the source code, and the type is not an interface; yet, adding the method results in undesirable coupling.

What exactly do C# LINQ Extension Methods do?

The Enumerable class implements LINQ’s typical query operators like as select, where, and so on. These methods are implemented as IEnumerable<T> interface.

Let me illustrate this with an example. In our Main method, we have the following code.

Although the Where() method in the above example does not belong to the ListT> class, we may still call it as if it did. Let us investigate why it is able to invoke it using the List<T> object. If you look up the definition of where method, you will discover the following.

As you can see in the signature, the where Where() method is implemented as an extension method on IEnumerable<T> interface and we know List<T> implements IEnumerable<T> interface. This is the reason why we are able to call the Where() method using the List<T> object.

Method Syntax is used in LINQ to invoke the extension methods of the Enumerable or Queryable static types. It is also known as Method Extension Syntax or Fluent. However, the compiler always translates query syntax to method syntax at compile time.

LINQ Query Operators?

LINQ Query Operators are a collection of additional ways for creating a query pattern. As building blocks for LINQ query expressions, these operators provide a variety of query functionality such as filtering, sorting, projection, aggregate, and so on.

The IEnumerable<T> and IQueryable<T> classes extension methods are what the LINQ language refers to as “standard query operators.They are defined in the System.Linq.Enumerable and System.Linq.Queryable classes.

Let us see What is IEnumerable in C#?

IEnumerable is an interface that is available in System.Collection namespace.The IEnumerable interface is a type of iteration design pattern. It means we can iterate on the collection of the type IEnumerable.the IEnumerable interface has one method called GetEnumerator which will return an IEnumerator that iterates through a collection.

The IEnumerable interface has also a child generic interface i.e. IEnumerable<T>. Let’s see the definition of the IEnumerable<T> interface.

All collection classes (generic and non-generic) in C# implement the IEnumerable interface.

Let us prove this by visiting the definition of List<T> generic collection class in the program mentioned below:

In C#, what is IQueryable?

the IQueryable is an interface and it is available in System.Linq namespace. The IQuerable interface is a child of the IEnumerable interface. So we can store IQuerable in a variable of type IEnumerable. The IQuerable interface has a property called Provider which is of type IQueryProvider interface. Let us see the definition of IQueryProvider.

The methods provided by the IQueryProvider are used to create all Linq Providers,The key element to understand is that in order to return a collection of type IQueryable, you must first call the AsQueryable() method on the collection, like we did in the preceding example.

C# LINQ Operators :

The LINQ Operators are simply a collection of extension methods used to create LINQ queries. These LINQ extension methods offer a lot of interesting features that we can apply to the data source. Filtering data, sorting data, grouping data, and so on are some of the characteristics.

Now we will demonstrate a few Linq operators such as filtering and projection.

LinQ Operator-Projection :

Projection is just the process used to choose data from a data source. You can choose the data in the same way (i.e. the original data in its original state). It is also possible to create a new type of data by executing operations on existing data.

  • Projection Methods  in LINQ

Two methods available in projection-

  1. Select
  2. SelectMany
Select Operator:

As we know, the Select clause in SQL allows us to choose which columns we want to retrieve, whether you want to retrieve all of the columns or just part of them.

Similarly, the LINQ Select operator allows us to specify the properties we want to retrieve, whether you want to retrieve all or some of the properties specified in the select operator. We can also conduct certain calculations using the usual LINQ Select Operator.

Let’s look at several instances to better grasp the select projection operator. We’ll be using a console programme in this case. So, first, develop a console programme called LINQDemo (you can give any meaningful name). Then create a new class file called Employee.cs. After you’ve added the Employee.cs class file, copy and paste the following code into it.

The Employee class was built with four properties: ID, FirstName, LastName, and Salary. We also wrote one static method that will return a list of employees and will serve as our data source.

Select –The operator uses a transform function to project values.

The Select operator consistently gives back an IEnumerable collection of elements that have been transformed, according to a transformation function. It is comparable to SQL’s Select clause, which generates a flat result set.

LinQ Operator-Filtering:

Filtering is the process of obtaining only those elements from a data source that satisfy the specified condition. It is also feasible to retrieve data from a data source with several conditions based on our business requirements.

LINQ provides two methods in C# that are used for filtering –

  • Where
  • OfType

In LINQ, the typical query operator “where” is classified as a Filtering Operator.

When we need to filter data from a data source based on some condition(s), we must use the where standard query operator in LINQ, exactly as we did in SQL using the where clause. So, to put it simply, it is used to filter data from a data source depending on some criterion (s).

The “where” clause always expects at least one condition, which we may provide using predicates.The conditions can be written using the following symbols:==, >=, <=, &&, ||, >, <,etc.

A predicate is simply a function that is used to test each element for a specific condition. Let me illustrate this with an example.

The Lambda expression (num => num > 5) is executed for each element in the “intList” collection. Then it will determine whether the number is more than or less than 5. If the number value is more than 5, the boolean value true is returned; otherwise, the boolean value false is returned.

Where is a LINQ functionality to filter data in a query with given criteria.

Where extension method also have second overload that includes index of current element in the collection. You can use that index in your logic if you need.

Where clause to filter out odd elements in the collection and return only even elements. Please remember that index starts from zero.

Conclusion:

With several examples, we examine extension methods in LINQ,IEnumerable,IQueryable, and Linq operators such as filtering and projection in this blog.

 

 

Author: Syed Haroon

Microsoft Certified Trainer |Azure Developer Associate | Technical Coordinator at Kovai.co having 13 years of experience in training on. Net Full Stack and Software Development, Pursuing Ph.D. in Computer Science, and Master of Computer Applications.

Get notified about any future events

Interested in learning more about TechMeet360 or knowing about any future events? Sign up below to get notified.

Back to Top