System.Linq.Enumerable.All – Better Know an Extension Method Part 2

During this series I will be investigating the purpose and uses of the Extension methods made available in the System.Linq namespace specifically for classes that implement IEnumerable. If you have any gems you have created for the extension in question drop a comment below as I would love to see what people are coming up with. In Part 2 I will be exploring the very simple but powerful All extension method described in the MSDN documentation as follows.

“Determines whether all elements of a sequence satisfy a condition”MSDN

This method is tricky to highlight its real value without using it with other methods and/or a linq query like below. Say we want to find all customers in a list where all of their orders are for more than $10.00.

var loyalCustomers = from customer in customers
                     where customer.Orders.All(order => order.TotalPrice >= 10)
                     select customer;

As you can see this is a powerful way of selecting from a list of parents based on the properties of children however it can also be used in an if statement.

var orderItems = new List<Product>()
{
    new Product() { Name="Ball", Stock = 0},
    new Product() { Name="Skipping Rope", Stock = 5},
    new Product() { Name="Comic", Stock = 3},
    new Product() { Name="Gum", Stock = 2}
};
 
if (!orderItems.All(product => product.Stock > 0))
{
    OrderStock(orderItems);
}

That is it All is a very simple extension method that can used very quickly to test an entire Enumeration.

System.Linq.Enumerable.Aggregate- Better Know an Extension Method Part 1

2 Responses to “System.Linq.Enumerable.All – Better Know an Extension Method Part 2”


  • Just nitpicking: Your first example isn’t calling System.Linq.Enumerable.All. It’s calling its twin brother System.Linq.Querable.All.

  • @Niki Thanks for point that out I will update this article with more accurate examples. Was really trying to find a useful example will have to think harder!

Leave a Reply