csharp

C# LINQ Operators with programming examples

Description:

C# LINQ Operators with Programming Examples:- In this article, I am going to show you the useful operators used in LINQ with step by step programming explanation.

With C# LINQ, Microsoft has integrated a new programming model into the .NET Framework, which the developer can use allows to query, manipulate and change data in the form of objects, SQL and XML.


Basics of the C# LINQ operators:

C# LINQ operators allow the developer to use a SQL-like query language for a wide variety of applications Use data sources. The C# LINQ operators are extended to the adapted to special data sources such as relational databases, XML data or objects.

C# LINQ Main source code:



C# LINQ Projection operators:

Projection operators assign the requested data to a result in order to then edit, or to be able to display.

Select operator:

The select operator transfers or projects the result to an object which is the interface IEnumerable <T> implemented and lists all selected data. In the following code, that’s all unique customer key.

Exampel1: using  the Select operator in c# linq:

Output:

The foreach loop demonstrates two output options. The first option is to use the Output System.Linq.Enumerable+WhereSelectArrayIterator2[data.Customer,&lt;&gt;f__AnonymousType01[System.String]], But which is a little awkward. The second option is to directly enter a data field which is of type string in this example. This is only possible when using the Select operator creates a new anonymous type to access the item.customerID property. It is also possible to work directly with lambda expressions.


SelectMany operator

If you want to have all order numbers output depending on a certain customer selection, then you need a dependency between the customer and his orders for the query. Here in after For example, all order numbers whose customers live in Germany are to be output. For this example, it makes sense to read through the subsection “Restriction Operator” first.

Exmaple2: using the SelectMany operator in c# linq:

Output:

 

In above example, it is noticeable that there are two from branches in the query, each of which is its own Area owns. Since a customer can have several orders, the query must be carried out in such a way that that the foreach loop can directly access the orders by going through c.orders the relationship to the higher-level query is created 1. The first from branch takes the customer constraint away via the where operator, the second from branch creates the relationship between customers and orders. The effect of the SelectMany operator becomes clear when used with lambda expressions. The following code generates a query that should display the orders of customers in Germany. The problem here is that the orders, in this example the c.orders, are again lists.

Output:

To be able to access this listing, you have to cascade a relationship as shown in above example or use the operator SelectMany as in the following code, which carries out the cascading.

Output:

To display data, it may also be useful to display the data via a relationship. Assuming that the customer key must also be shown for each order number. To do this, you need a result that returns both amounts of data: that of the customer and that of the order. To do this, you create an anonymous type that contains both data.

Output:

C# LINQ Restriction operator:

The Where operator is a restriction operator that determines which data should be displayed and thus applying a kind of filter to the query. For example, if you want to know which customers are based in Germany, you choose select the country Germany via the Where operator.

Example3: using the Where operator in c# linq:

Output:


Sort operators in C# LINQ:

Data often needs to be edited or displayed in a specific order. This is what in LINQ provides various sorting operators, the data in ascending, descending or vice versa Sort order.

OrderBy:

The two operators OrderBy and OrderByDescending sort data in ascending or descending order. In the example4 shows all order numbers from customers in Germany in ascending order issued.

Example4: using the OrderBy operator in c# linq

Output:

The following code produces the same result using lambda expressions.

If you want to display a list in descending order, the OrderByDescending operator comes into play Commitment. The following two code examples demonstrate the different notations for the Use of the OrderByDescending operator.

Output:

The descending keyword comes after the field to be sorted. The alternative would be as follows Syntax:

Output:

ThenBy and ThenByDescending operators:

The two operators ThenBy and ThenByDescending allow the developer to search for more than one field sort by. The sorting direction can be different for each data field.

Exmaple5:  using the Sorting multiple data fields in c# linq:

Output:


Reverse operator:

If you want to output the data in the reverse order, you can use the reverse operator on the Result will be applied.

Example6: using The reverse operator in c# linq:

Output:

Grouping operators in C# LINQ:

It is often necessary to group the data for better clarity. C# LINQ provides for this purpose ready a grouping operator.

GroupBy operator

The GroupBy operator can be used to group data to provide a clearer view of the data received. Example7 shows all customer keys that exist within a country. This is done the grouping operator applied via c.country.

Example7: using GroupBy operator in C# linq:

Output:

The keyword into is used for better readability. The following code snippet without the keywords into and select, returns the same result as in the above example.

Link operators in C# LINQ:

Join operators allow two sequences to be linked using a key. So 1: n or n: m relationships can be established.

Join operator

If you want to establish a relationship between two collections of data objects2 that have a key are linked, the join operator is used. in our Main source code, the two classes Order and Product have a key productID, via which the link is made. The following code gives the order date, the order and the Product key.

Exmaple8: using the Join operator in c# linq:

Output:

The products are integrated into the query via the join clause and the keyword on becomes the link is created. Since there is a relationship between c.orders and products, it is called c.orders as the “outer sequence” and products as the “inner sequence” of the data via a so-called external and internal linkage are interconnected.

The join operator takes four arguments to join the data. About the statement SelectMany (c => c.orders) determines the outer sequence, with products the inner sequence. o => o.productID is the outer key and p.productID is the inner key for linking the data.



GroupJoin operator:

The GroupJoin operator creates a hierarchical representation of the data that is based on the outer sequence composed of data from the inner sequence. To create a hierarchy of data, Several options are available in c# LINQ. Exmaple9 shows one possible query.

Exmple9: using the GroupJoin operator  in c# linq:

Output:

In order to be able to display all products from products hierarchically, the outer sequence must be the listing products to be. The inner sequence is the orders via c.orders, which via the join clause with the Products can be linked via the product key productID. The GroupJoin operator is accessed via the Put expression into in the query. The same result can also be obtained directly via the GroupJoin operator using lambda expressions:

Set operators in C# LINQ:

The C# LINQ set operators are used for query operations on data that occurs multiple times in a sequence are available and should remain or be omitted for the display of the data. A typical set operator is distinct, which combines the same data that occurs several times in a sequence.

Distinct operator

The Distinct operator uses a certain query technique to prevent duplicates in a sequence being represented. Looking at the example from our main source code, it is noticeable that the two customers ABC and AAA have bought the same product twice. Would you like to know which products are from all customers were bought, the information on how often the products were bought is not relevant.

Example10: using Distinct operator in C# linq:

Output:

Union operator:

The C# LINQ operator union combines the data of two sequences without creating duplicates in the output. Suppose the two customers XYZ and ABC enter into an order cooperation and want to deal with all of them ordered products receive a two percent discount, so you need the products, both customers have ordered, but without duplicates

Example11: using the union operator in c# linq:

 

Output:


Intersect and Except operators in C# LINQ:

The intersect operator returns the result that is the same in both sequences. As you can seen in  Example12 the product number or productID with the value 999.

Example12: using the Intersect operator in c# linq:

Output:

The result of the Except operator is a sequence whose values ​​are in the first sequence and not in occur in the second sequence. In the values ​​of the sequences XYZ {322,522,999} and ABC {31,52,999} the third element with the value 999 appears twice, so that the result sequence is {322,522}. The value 52 is in the second sequence and is not included in the output, although it is not in the first sequence appears. The first sequence is therefore the leading sequence of an Except query.

Example13: using the Except operator in c# linq:

Output:

Aggregate operators in C# LINQ:

Aggregates or aggregate functions allow the developer to make calculations from a data sequence, Generate simplifications or summaries of data.


Count operator:

With the count operator it is possible to determine a number of data elements. Our main source code looks one that a customer has several orders. If one now wants the number of orders per Output customer, the desired output can be generated using the count operator.

Example14: using the Count operator in c# linq:

Output:

The count operator is often used in combination with the join operator or the GroupBy operator used. For example, if you want to know how many orders have been placed for each product, then will this information is generated using the join operator. Example15  gives the Number of orders from.

Example15: using the Count operator over a join operator in c# linq:

Output:

The LongCount operator is used in the same way as the Count operator and is used for very large collections or sequences used.

Sum operator

The sum operator forms the sum over a sequence. Any type of number can be used become. In the example from our main source code, the unitPrice of the Product class is of type double. You don’t want to only output the number of orders per product as shown in example15, but also the converted sum across all orders, this can be done via the sum operator. The following Code shows the order amount behind the number of orders.

Example16: using the Sum operator in c# linq:

Output:

Min and Max operator

To determine the minimum or maximum value in a sequence, the two operators Min and Max used. For example, if you want the cheapest and most expensive product in the product range you can use the two operators Min and Max as in example17.

Example17: using the Min and Max operator in c# linq:

Output:

Average operator:

In order to be able to calculate an average of values ​​in a sequence, one needs the average Operator. Example18 calculates how much the products in the range averaged costs.

Example18: using the Average operator in c# linq:

Output:


Generation operators in C# LINQ:

As the name suggests, the generation operators create new sequences – for example for a specific selection range or a specific number of repeating values ​​a Sequence. Generation operators are often used as auxiliary operators in queries.

DefaultIfEmpty and Empty operators:

If a query returns an empty sequence, this can be given a standard value or a standard object by passing the default value as an argument to the DefaultIfEmpty operator. Example19 should list all product keys whose values ​​are less than 10. But there is no in the product range such a key exists, the default value -1 is returned.

Example19: DefaultIfEmpty operator in c# linq:

Output:

If you want to save values ​​from a form mask in a sequence, it can often make sense be to create an empty sequence. The Empty operator can be used for this by using as generic type transfers the type of the class for which the sequence is to be generated.

Range operator:

If you want to work with a certain range of values ​​within a query, it is recommended to use it of the range operator. Example20 shows the product key and date for all orders placed in the period were made i.e  from  month abc to xyz.

Example20: using the Range operator in c# linq:

Output:



Repeat operator:

The repeat operator returns a sequence n times. Such queries can occur, for example, if you want to output the weekday names in a year. Since the year consists of 52 weeks, will the sequence from Monday to Sunday may be returned 52 times.  Example21 gives all the product keys that greater than 60, three times

Example21: using the Repeat operator in c# linq:

Output:

Quantification operators in C# LINQ:

Quantification operators are used when considering the existence of certain data in a sequence want to determine or to make queries easier.

Any operator

The operator Any searches for a specific element in a collection and returns a Boolean as the result Value back. If the element exists, true is returned. The operator Any breaks on the first search for the matching item.

Example22: using the Any operator in c# linq:

Output:

Exmaple22 checks in the sequence result1 whether a country with the string “Germany” exists and returns the result as a Boolean value.

All operator:

The All operator checks all data for a certain condition that is passed as a parameter. For example, you want to check whether all orders have been made after August 1st, 1996 a possible query might look like example23.

Example23: using the All-Operator in c# linq

Output:

Contains operator:

If you are working with complete lists that have to be queried, then the Contains operator comes to the Commitment. It checks whether certain elements appear in a sequence. Example24 gives all customers that are in the countries list, i.e. in Germany or Sweden.

Example24: Using the Contains operator in c# linq:

Output:


Partitioning operators in C# LINQ:

Partitioning operators are used to segment data that meets a specific condition or condition follow a rule.

Take operator:

The Take operator is used when, for example, a fixed number of data elements is returned would like to. It is important to sort the data in order to use the take operator as an argument a number is passed to also receive the desired data.

Example25: using the Take operator in c# linq:

Output:

Example25  gives the product keys and the quantity of the three products that sell best to have. The let operator is used as a placeholder for the number of products sold that will then be used for the sorting can be used.

TakeWhile operator:

The TakeWhile operator works like the take operator, except that a condition or condition is included in the argument. Calculation can pass. For example, if you need all products whose price is greater than 15.0, you can solve this as shown in Example26.

Example26: using the TakeWhile operator in c# linq:

Output:

The sorting of the data also plays an important role here, since the TakeWhile operator works with the Output ends once the condition is met or not met (depending on which condition in the Argument is given). If you omit the keyword descending in example26, you get a blank output with no data.

Skip operator:

The skip operator skips the specified number of elements before adding the further data elements or outputs the sequences. Example27 skips the first two results from example26  and the output begins with the third result.

Example27: using the Skip operator in c# linq:

Output:

SkipWhile operator:

As with the TakeWhile operator, the SkipWhile operator can be used to produce results according to a specific Condition to be skipped. Here, too, the sorting is of crucial importance.

Example28: using the SkipWhile operator in c# linq:

Output:

exmaple28 displays all products that have a product key number greater than 50. The Elements of a sequence are skipped until a false is returned. Since this is a represents negative logic, the return value ret is negated in Example28.


Element operators in C# LINQ:

Element operators extract individual data from a sequence that follows a certain condition.

ElementAt and ElementAtOrDefault operators:

The ElementAt operator extracts index-based data. The sorting of the data also plays a role here essential role. Example29 extracts the third piece of data and prints it.

Example29: using the ElementAt operator in c# linq:

Output:

First and FirstOrDefault operators:

The two operators First and FirstOrDefault return the first element of a sequence.

Example30: using the First and FirstOrDefault operator in c# linq:

Output:

Last and LastOrDefault operators:

The two operators Last and LastOrDefault return the last element of a sequence.

Example31: using the Last and LastOrDefault operator in c# linq

Output:

Single and SingleOrDefault operator:

The single operator extracts an element that follows a certain condition. Is with a query assuming that there are conditions that are not met is the use of the SingleOrDefault Operators recommended, otherwise an error will be triggered. Example32 gives the product with the Product key 63.

Example32: using the Single and SingleOrDefault operator in c# linq:

output:

 

Related Articles

Leave a Reply

Your email address will not be published. Required fields are marked *

Back to top button