More LINQ: boolean tests on sequences
Got a match?Sometimes we don’t actually want to examine the elements returned by a query. In fact, we’d rather not spend the machine cycles to retrieve all the elements that match a particular query. Instead, the Any() and All() methods perform some of the work of a query and return Boolean values that tell you if there was a match.
This query determines if at least 1 of the elements in the source contains the string “ei”:
string[] words = { "believe", "relief", "receipt", "field" };
bool iAfterE = words.Any(w => w.Contains("ei"));If you can test a condition, you can use the results of that query as the predicate to a new select.
(huh?)
Well, the following query explains. Suppose I want to produce a collection of every product category where at least one product is out of stock. We’ll run a query of all the products, and group them by category. We’ll push the results of that query into a new query. In this second query, if any of the products are out of stock, it creates a new object where the first property is the category key, and the second property is the sequence of products (one of which is out of stock):
// Additional comments mine:
List<Product> products = GetProductList();
var productGroups =
from p in products // Query all the products
group p by p.Category into g // Group by category. And, examine the units in stock:
where g.Any(p => p.UnitsInStock == 0) // If there are products out of stock
select new { Category = g.Key, Products = g }; // Create a sequence of the entire group
Similar to “Any”, the LINQ sequence libraries contain “All”, which returns true if every source element matches the predicate. This simple version determines if every number in the sequence is odd:
int[] numbers = { 1, 11, 3, 19, 41, 65, 19 };
bool onlyOdd = numbers.All(n => n % 2 == 1);As with Any, you can use All to chain queries to each other and return the groups of products where all products have some items in stock:
List<Product> products = GetProductList();
var productGroups =
from p in products
group p by p.Category into g
where g.All(p => p.UnitsInStock > 0)
select new { Category = g.Key, Products = g };
Next, we’ll start counting and aggregating the results of queries. (There’s a lot more to learn)
Part 1The general query syntax
Part 2The one where I discuss Object and Collection Initializers
Part 3The one where I finish restriction operators
Part 4Beginning to discuss projections
Part 5Anonymous types and projections
Part 6Discussing indexed, filtered, and compound queries
Part 7Finishing up the projection items
Part 8Projection operators and extension methods
Part 9OrderBy, ThenBy, and Descending, oh my
Part 10Grouping operators, and building nested groups
Part 11Set Operations, You bet
Part 12Conversions: caching collections
Part 13Where you at item, wher you at?