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:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 |
using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Text; namespace data { public class Customer { public string customerID; public string companyName; public string country; public Order[] orders; } public class Order { public int orderID; public DateTime orderDate; public string shipCountry; public int productID; } public class Product { public int productID; public double unitPrice; public string name; } public class Program { public static void Main(string[] args) { Product p1 = new Product { productID = 31, unitPrice = 12.5, name = "USB" }; Product p2 = new Product { productID = 52, unitPrice = 15.9, name = "LCD" }; Product p3 = new Product { productID = 52, unitPrice = 90.5, name = "PS4" }; Product p4 = new Product { productID = 63, unitPrice = 7.0, name = "LCD" }; Product p5 = new Product { productID = 9999, unitPrice = 146.45, name = "new Product" }; Product[] products = new Product[] { p1, p2, p3,p4,p5 }; //Orders Order[] orderXYZ = new Order[] { new Order {orderID = 10643, orderDate = DateTime.Parse("10-06-2021"), shipCountry = "Germany", productID = 322}, new Order {orderID = 10692, orderDate = DateTime.Parse("10-06-2021"), shipCountry = "Germany", productID = 522}, new Order {orderID = 10702, orderDate = DateTime.Parse("10-06-2021"), shipCountry = "Germany", productID = 999}, }; Order[] orderABC = new Order[] { new Order {orderID = 1033, orderDate = DateTime.Parse("10-06-2021"), shipCountry = "Sweden", productID = 31}, new Order {orderID = 10453, orderDate = DateTime.Parse("10-06-2021"), shipCountry = "Sweden", productID = 52}, new Order {orderID = 10234, orderDate = DateTime.Parse("10-06-2021"), shipCountry = "Sweden", productID = 999}, }; Order[] orderAAA = new Order[] { new Order {orderID = 1022, orderDate = DateTime.Parse("10-06-2021"), shipCountry = "France", productID = 31}, new Order {orderID = 10445, orderDate = DateTime.Parse("10-06-2021"), shipCountry = "France", productID = 52}, new Order {orderID = 10199, orderDate = DateTime.Parse("10-06-2021"), shipCountry = "France", productID = 9999}, }; Order[] orderSSS = new Order[] { }; //Customers Customer[] customers = new Customer[] { new Customer {customerID = "XYZ", companyName = "Programmingdigest", country = "Germany", orders = orderXYZ}, new Customer {customerID = "ABC", companyName = "Electroniclinic", country = "Sweden", orders = orderABC}, new Customer {customerID = "AAA", companyName = "QQQ", country = "France", orders = orderAAA}, new Customer {customerID = "SSS", companyName = "EEE", country = "Germany", orders = orderSSS} }; //paste here operation code Console.ReadKey(); } } } |
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:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 |
using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Text; namespace data { public class Customer { public string customerID; public string companyName; public string country; public Order[] orders; } public class Order { public int orderID; public DateTime orderDate; public string shipCountry; public int productID; } public class Product { public int productID; public double unitPrice; public string name; } public class Program { public static void Main(string[] args) { Product p1 = new Product { productID = 31, unitPrice = 12.5, name = "USB" }; Product p2 = new Product { productID = 52, unitPrice = 7.0, name = "LCD" }; Product p3 = new Product { productID = 9999, unitPrice = 146.45, name = "new Product" }; Product[] products = new Product[] { p1, p2, p3 }; //Orders Order[] orderXYZ = new Order[] { new Order {orderID = 10643, orderDate = DateTime.Parse("02-10-2021"), shipCountry = "Germany", productID = 31}, new Order {orderID = 10692, orderDate = DateTime.Parse("02-10-2021"), shipCountry = "Germany", productID = 52}, new Order {orderID = 10702, orderDate = DateTime.Parse("02-10-2021"), shipCountry = "Germany", productID = 9999}, }; Order[] orderABC = new Order[] { }; Order[] orderAAA = new Order[] { }; Order[] orderSSS = new Order[] { }; //Customers Customer[] customers = new Customer[] { new Customer {customerID = "XYZ", companyName = "Programmingdigest", country = "Germany", orders = orderXYZ}, new Customer {customerID = "ABC", companyName = "Electroniclinic", country = "Sweden", orders = orderABC}, new Customer {customerID = "AAA", companyName = "QQQ", country = "France", orders = orderAAA}, new Customer {customerID = "SSS", companyName = "EEE", country = "Germany", orders = orderSSS} }; var result = from c in customers select new { c.customerID }; foreach (var item in result) { Console.WriteLine(item.ToString()); Console.WriteLine(item.customerID); } Console.ReadKey(); } } } |
Output:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
{ customerID = XYZ } XYZ { customerID = ABC } ABC { customerID = AAA } AAA { customerID = SSS } SSS |
The foreach loop demonstrates two output options. The first option is to use the Output System.Linq.Enumerable+WhereSelectArrayIterator2[data.Customer,<>f__AnonymousType0
1[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:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
var orders1 = from c in customers where c.country == "Germany" from o in c.orders select o; foreach (var item in orders1) { Console.WriteLine(item.orderID); } Console.ReadKey(); |
Output:
1 2 3 4 5 |
10643 10692 10702 |
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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
// Lambda expression without SelectMany operator var orders2 = customers .Where(c => c.country == "Germany") .Select(c => c.orders); foreach (var item in orders2) { Console.WriteLine(item); } |
Output:
1 2 3 |
data.Order[] data.Order[] |
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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
// Lambda expression with SelectMany operator var orders3 = customers .Where(c => c.country == "Germany") .SelectMany(c => c.orders); foreach (var item in orders3) { Console.WriteLine(item.orderID); } |
Output:
1 2 3 4 5 |
10643 10692 10702 |
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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
// display data from different objects var orders1 = from c in customers where c.country == "Germany" from o in c.orders select new { o, c }; foreach (var item in orders1) { Console.WriteLine(item.c.customerID + " " + item.o.orderID); } |
Output:
1 2 3 4 5 |
XYZ 10643 XYZ 10692 XYZ 10702 |
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:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
var result1 = from c in customers where c.country == "Germany" select new { c.customerID }; foreach (var item in result1) { Console.WriteLine(item.ToString()); Console.WriteLine(item.customerID); } |
Output:
1 2 3 4 5 6 7 |
{ customerID = XYZ } XYZ { customerID = SSS } SSS |
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
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
var orders1 = from c in customers where c.country == "Germany" from o in c.orders orderby o.orderID select o; foreach (var item in orders1) { Console.WriteLine(item.orderID); } |
Output:
1 2 3 4 5 |
10643 10692 10702 |
The following code produces the same result using lambda expressions.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
var orders2 = customers .Where(c => c.country == "Germany") .SelectMany(c => c.orders) .OrderBy(o => o.orderID); foreach (var item in orders2) { Console.WriteLine(item.orderID); } |
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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
var orders1 = // simple query from c in customers where c.country == "Germany" from o in c.orders orderby o.orderID descending select o; foreach (var item in orders1) { Console.WriteLine(item.orderID); } |
Output:
1 2 3 4 5 |
10702 10692 10643 |
The descending keyword comes after the field to be sorted. The alternative would be as follows Syntax:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
var orders2 = customers .Where(c => c.country == "Germany") .SelectMany(c => c.orders) .OrderByDescending(o => o.orderID); foreach (var item in orders2) { Console.WriteLine(item.orderID); } |
Output:
1 2 3 4 5 |
10702 10692 10643 |
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:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
var result1 = from c in customers where c.country == "Germany" from o in c.orders orderby c.customerID, o.orderDate descending select new { c, o }; foreach (var item in result1) { Console.WriteLine(item.c.customerID + " " + item.o.orderID + " " + item.o.orderDate); } |
Output:
1 2 3 4 5 |
XYZ 10643 10/6/2021 12:00:00 AM XYZ 10692 10/6/2021 12:00:00 AM XYZ 10702 10/6/2021 12:00:00 AM |
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:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
var result1 = ( from c in customers where c.country == "Germany" from o in c.orders orderby c.customerID, o.orderDate descending select new { c, o } ).Reverse(); foreach (var item in result1) { Console.WriteLine(item.c.customerID + " " + item.o.orderID + " " + item.o.orderDate); } |
Output:
1 2 3 4 5 |
XYZ 10702 10/6/2021 12:00:00 AM XYZ 10692 10/6/2021 12:00:00 AM XYZ 10643 10/6/2021 12:00:00 AM |
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:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
var result1 = from c in customers group c by c.country into cCountry select cCountry; foreach (var item in result1) { Console.WriteLine(item.Key); foreach (var subitem in item) { Console.WriteLine("\t" + subitem.customerID); } } |
Output:
1 2 3 4 5 6 7 8 9 10 11 12 13 |
Germany XYZ SSS Sweden ABC France AAA |
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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
var result1 = from c in customers group c by c.country; If you use the notation via a lambda expression, you can see the direct application of the GroupBy operators. var result2 = customers .GroupBy(c => c.country); foreach (var item in result2) { Console.WriteLine(item.Key); foreach (var subitem in item) { Console.WriteLine("\t" + subitem.customerID); } } |
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:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
var result1 = from c in customers where c.customerID == "XYZ" from o in c.orders join p in products on o.productID equals p.productID select new { o.orderID, o.orderDate, p.productID }; foreach (var item in result1) { Console.WriteLine(item.orderDate + " " + item.orderID + " " + item.productID); } |
Output:
1 2 3 4 5 |
10/6/2021 12:00:00 AM 10643 31 10/6/2021 12:00:00 AM 10692 52 10/6/2021 12:00:00 AM 10702 999 |
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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
// Lambda expression with join operator var result2 = customers .Where (c => c.customerID == "XYZ") .SelectMany (c => c.orders) .Join ( products, o => o.productID, p => p.productID, (o, p) => new { o.orderID, o.orderDate, p.productID } ); foreach (var item in result2) { Console.WriteLine(item.orderDate + " " + item.orderID + " " + item.productID); } |
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:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 |
var result3 = from p in products join o in ( from c in customers from o in c.orders select o ) on p.productID equals o.productID into ox select new { p.name, p.productID, Orders = ox }; foreach (var item in result3) { Console.WriteLine(item.productID + " " + item.name); foreach (var item2 in item.Orders) { Console.WriteLine("\t" + item2.orderID); } } |
Output:
1 2 3 4 5 6 7 8 9 10 11 |
31 USB 10643 52 LCD 10692 999 new Product 10702 |
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:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 |
// Lambda expression with GroupJoin operator var result4 = products .GroupJoin ( customers.SelectMany (c => c.orders), p => p.productID, o => o.productID, (p, ox) => new {p.name, p.productID, Orders = ox} ); foreach (var item in result4) { Console.WriteLine (item.productID + "" + item.name); foreach (var item2 in item.Orders) { Console.WriteLine ("\t" + item2.orderID); } } |
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:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
var result = from c in customers from o in c.orders join p in products on o.productID equals p.productID select new { c.customerID, p.productID }; foreach (var item in result.Distinct()) { Console.WriteLine(item.customerID + " " + item.productID); } |
Output:
1 2 3 4 5 |
XYZ 31 XYZ 52 XYZ 999 |
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:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 |
Console.WriteLine("Customer XYZ"); var c1 = from c in customers where c.customerID == "XYZ" from o in c.orders select new { o.productID }; foreach (var i1 in c1) { Console.WriteLine(i1.productID); } Console.WriteLine("Customer ABC"); var c2 = from c in customers where c.customerID == "ABC" from o in c.orders select new { o.productID }; foreach (var i2 in c2) { Console.WriteLine(i2.productID); } Console.WriteLine("Union"); var result = c1.Union(c2); foreach (var item in result) { Console.WriteLine(item.productID); } |
Output:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
Customer XYZ 322 522 944 Customer ABC 31 52 999 Union 322 522 944 31 52 999 |
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:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 |
Console.WriteLine("Customer XYZ"); var c1 = from c in customers where c.customerID == "XYZ" from o in c.orders select new { o.productID }; foreach (var i1 in c1) { Console.WriteLine(i1.productID); } Console.WriteLine("Customer ABC"); var c2 = from c in customers where c.customerID == "ABC" from o in c.orders select new { o.productID }; foreach (var i2 in c2) { Console.WriteLine(i2.productID); } Console.WriteLine("Intersect"); var result = c1.Intersect(c2); foreach (var item in result) { Console.WriteLine(item.productID); } |
Output:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
Customer XYZ 322 522 999 Customer ABC 31 52 999 Intersect 999 |
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:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 |
Console.WriteLine("Customer XYZ"); var c1 = from c in customers where c.customerID == "XYZ" from o in c.orders select new { o.productID }; foreach (var i1 in c1) { Console.WriteLine(i1.productID); } Console.WriteLine("Customer ABC"); var c2 = from c in customers where c.customerID == "ABC" from o in c.orders select new { o.productID }; foreach (var i2 in c2) { Console.WriteLine(i2.productID); } Console.WriteLine("Except"); var result = c1.Except(c2); foreach (var item in result) { Console.WriteLine(item.productID); } |
Output:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
Customer XYZ 322 522 999 Customer ABC 31 52 999 Except 322 522 |
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:
1 2 3 4 5 6 7 8 9 10 11 12 13 |
var result = from c in customers select new { c.customerID, c.companyName, numberOfOrders = c.orders.Count() }; foreach (var item in result) { Console.WriteLine(item.customerID + " " + item.companyName + " " + item.numberOfOrders); } |
Output:
1 2 3 4 5 6 7 |
XYZ Programmingdigest 3 ABC Electroniclinic 3 AAA QQQ 3 SSS EEE 0 |
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:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 |
var result2 = from p in products join o in ( from c in customers from o in c.orders select o ) on p.productID equals o.productID into ox select new { p.name, p.productID, Orders = ox, numberOfOrders = ox.Count() }; foreach (var item in result2) { Console.WriteLine(item.productID + " " + item.name + " " + item.numberOfOrders); foreach (var item2 in item.Orders) { Console.WriteLine("\t" + item2.orderID); } } |
Output:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
31 USB 2 1033 1022 52 LCD 2 10453 10445 9999 new Product 1 10199 |
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:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 |
var result3 = from p in products join o in ( from c in customers from o in c.orders select o ) on p.productID equals o.productID into ox select new { p.name, p.productID, sumOfProducts = ox.Sum(sum => p.unitPrice), Orders = ox, numberOfOrders = ox.Count() }; foreach (var item in result3) { Console.WriteLine(item.productID + " " + item.name + " " + item.numberOfOrders + " " + item.sumOfProducts); foreach (var item2 in item.Orders) { Console.WriteLine("\t" + item2.orderID); } } |
Output:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
31 USB 2 25 1033 1022 52 LCD 2 14 10453 10445 9999 new Product 1 146.45 10199 |
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:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
var result4 = from p in products select p.unitPrice; Console.WriteLine(result4.Min()); var result5 = from p in products select p.unitPrice; Console.WriteLine(result5.Max()); |
Output:
1 2 3 |
7 146.45 |
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:
1 2 3 4 5 6 7 |
var result6 = from p in products select new { p.unitPrice }; Console.WriteLine(result6.Average(p => p.unitPrice)); |
Output:
1 |
55.3166666666667 |
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:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
var result3 = products.AsQueryable() .Where(p => p.productID < 10) .Select(pid => pid.productID) .DefaultIfEmpty(-1); foreach (var item in result3) { Console.WriteLine(item); } |
Output:
1 |
-1 |
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.
1 |
var result4 = Enumerable.Empty <Product> (); |
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:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 |
var result = Enumerable.Range(3, 8) .SelectMany ( month => ( from c in customers from o in c.orders where o.orderDate.Month == month select new { o.orderID, o.orderDate } ) ); foreach (var item in result) { Console.WriteLine(item.orderID + " " + item.orderDate); } |
Output:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
10643 10/6/2021 12:00:00 AM 10692 10/6/2021 12:00:00 AM 10702 10/6/2021 12:00:00 AM 1033 10/6/2021 12:00:00 AM 10453 10/6/2021 12:00:00 AM 10234 10/6/2021 12:00:00 AM 1022 10/6/2021 12:00:00 AM 10445 10/6/2021 12:00:00 AM 10199 10/6/2021 12:00:00 AM |
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:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
var result2 = Enumerable.Repeat ( from c in customers from o in c.orders where o.productID > 60 select new { o.productID }, 3 ) .SelectMany(pid => pid); foreach (var item in result2) { Console.WriteLine(item.productID); } |
Output:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
322 522 999 999 9999 322 522 999 999 9999 322 522 999 999 9999 |
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:
1 2 3 4 5 6 7 8 9 |
var result1 = from c in customers select c; bool exists1 = result1.Any(c => c.country == "Germany"); Console.WriteLine(exists1) |
Output:
1 |
True |
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
1 2 3 4 5 6 7 8 9 10 11 |
var result2 = from c in customers from o in c.orders select o; bool exists2 = result2.All(o => o.orderDate > DateTime.Parse("01-08-1996")); Console.WriteLine(exists2); |
Output:
1 |
True |
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:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
List<string> countries = new List<string>(); countries.Add("Germany"); countries.Add("Sweden"); var result3 = from c in customers where countries.Contains(c.country) select c; foreach (var item in result3) { Console.WriteLine(item.customerID); } |
Output:
1 2 3 4 5 |
XYZ ABC SSS |
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:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 |
var result1 = from c in customers from o in c.orders join p in products on o.productID equals p.productID group p by p.productID into pid let cnt = pid.Count() orderby cnt descending select pid; foreach (var item in result1.Take(3)) { foreach (var item2 in item.Distinct()) { Console.Write(item2.productID + " "); } Console.WriteLine(item.Count()); } |
Output:
1 2 3 4 5 |
31 2 52 2 9999 1 |
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:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 |
var result2 = ( from p in products orderby p.unitPrice descending select new { p.productID, p.name, p.unitPrice } ).TakeWhile ( up => { bool ret = up.unitPrice > 15.0; return ret; } ); foreach (var item in result2) { Console.WriteLine(item.name + " " + item.productID + " " + item.unitPrice); } |
Output:
1 |
new Product 9999 146.4 |
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:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 |
var result2 = ( from p in products orderby p.unitPrice descending select new { p.productID, p.name, p.unitPrice } ).TakeWhile ( up => { bool ret = up.unitPrice > 15.0; return ret; } ).Skip(2); foreach (var item in result2) { Console.WriteLine(item.name + " " + item.productID + " " + item.unitPrice); } |
Output:
1 |
LCD 52 15.9 |
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:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 |
var result3 = ( from p in products orderby p.productID select new { p.productID, p.name, p.unitPrice } ).SkipWhile ( sk => { bool ret = sk.productID > 50; return !ret; } ); foreach (var item in result3) { Console.WriteLine(item.name + " " + item.productID + " " + item.unitPrice); } |
Output:
1 2 3 4 5 6 7 |
LCD 52 15.9 PS4 52 90.5 LCD 52 7 new Product 9999 146.45 |
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:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
var result1 = from p in products orderby p.unitPrice descending select new { p.productID, p.name, p.unitPrice }; Console.WriteLine(result1.ElementAt(3)); Console.WriteLine(result1.ElementAt(3).name); Console.WriteLine(result1.ElementAt(3).productID); Console.WriteLine(result1.ElementAt(3).unitPrice); |
Output:
1 2 3 4 5 6 7 |
{ productID = 31, name = USB, unitPrice = 12.5 } USB 31 12.5 |
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:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
var result3 = from p in products orderby p.unitPrice descending select new { p.productID, p.name, p.unitPrice }; Console.WriteLine(result3.First()); Console.WriteLine(result3.FirstOrDefault() == null ? "-" : result3.First().name); Console.WriteLine(result3.FirstOrDefault() == null ? -1 : result3.First().productID); Console.WriteLine(result3.FirstOrDefault() == null ? 0.00 : result3.First().unitPrice); |
Output:
1 2 3 4 5 6 7 |
{ productID = 9999, name = new Product, unitPrice = 146.45 } new Product 9999 146.45 |
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
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
var result4 = from p in products orderby p.unitPrice descending select new { p.productID, p.name, p.unitPrice }; Console.WriteLine(result4.Last()); Console.WriteLine(result4.LastOrDefault() == null ? "-" : result4.Last().name); Console.WriteLine(result4.LastOrDefault() == null ? -1 : result4.Last().productID); Console.WriteLine(result4.LastOrDefault() == null ? 0.00 : result4.Last().unitPrice); |
Output:
1 2 3 4 5 6 7 |
{ productID = 52, name = LCD, unitPrice = 7 } LCD 52 7 |
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:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
var result5 = from p in products orderby p.unitPrice descending select new { p.productID, p.name, p.unitPrice }; Console.WriteLine(result5.Single(p => p.productID == 63)); Console.WriteLine(result5.SingleOrDefault(p => p.productID == 63) == null ? "-" : result5.Single(p => p.productID == 63).name); Console.WriteLine(result5.SingleOrDefault(p => p.productID == 63) == null ? 0.00 : result5.Single(p => p.productID == 63).unitPrice); |
output:
1 2 3 4 5 |
{ productID = 63, name = LCD, unitPrice = 7 } LCD 7 |