Generation operators:
Range: Given a start and count generates a list of integers.
Generates integers 3,4 … 12.
Repeat: Is similar to replicate() –but not limited to strings- and generates a list of a given element (either a single element or not) repeating it N times.
Enumerable( 'A', 5).Dump(); // Char A 5 times
Enumrable.Repeat(1, 3).Dump(); // int 1 3 times
var o = Customers.Single( c => c.CustomerID == "ALFKI" ); // Single is a method specifying that the result is a single element
Enumerable.Repeat(o,10).Dump(); Customers o 10 Times
var customers = Customers.Where( c => c.Country == "USA" );
Enumerable.Repeat(customers, 3).Dump(); // a series of customers repeated 3 times
Note that Repeat() repeats the given source which is a singleton element or a collection.
Empty: Generates an "empty" sequence of a given type of source. Though it is "empty", it is still a representation of given type rather than NULL.
customers.Dump(); // nothing
customers.Count().Dump(); // 0
Quantifier Operators:
Contains: Returns true if a given sequence contains a given element. T-SQL counterpart is IN, Exists.
Customers.Where( c => countries.Contains(c.Country)).Dump();
Selects customers where Customers.Country IN ("USA","UK","Germany").
Any: Returns true if a sequence have "any" elements. T-SQL counterpart is Exists, IN.
Returns all Customers that has at least one Order.
Returns all customers who have an Order with at least 6 items. Here is the result set using Northwind (picture cut):
As you may have noticed Any() can do what Contains() do. For example we could rewrite Contains sample:
Customers
.AsEnumerable()
.Where( c => countries.Any( cn => cn == c.Country )).Dump();
However in case of an IQueryable (like Linq To SQL or Entity Framework) Contains() is supported to have a local sequence while Any() is not supported - and its syntax is easier for this sample.
All: All is like Any() but always have a filter condition where all elements of a sequence should match for All() to return true.
.Where( o => o.OrderDetails
.All( od => od.Product.Category.CategoryName == "Beverages" ))
Selects all the orders where all order items are from "Beverages" category. You can take a look what those order ID, product name and category names are using the methods we learned earlier:
.Where( o => o.OrderDetails
.All( od => od.Product.Category.CategoryName == "Beverages" ))
.SelectMany(
o => o.OrderDetails,
(o, od) => new
{
OrderID = o.OrderID,
Product = od.Product.ProductName,
Category = od.Product.Category.CategoryName
})
.OrderBy( o => o.OrderID )
0 comments:
Post a Comment