System.Linq.Enumerable.Any – Better Know an Extension Method Part 3

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 3 I will be exploring the very simple Any extension method described in the MSDN documentation as follows.

“Determines whether a sequence contains any elements.”MSDN

When I first started looking at Any it seemed really strange at first, the first override just returns true if the Enumeration is greater than 0 which quite frankly is bizarre since its a direct copy of Count. It would just prove a neater way to write Linq expressions rather than the alternative using Count.

 
var orders = new List<Order>()
{
     new Order() {Total = 123.23},
     new Order() {Total = 512},
     new Order() {Total = 123.23},
     new Order() {Total = 5172.34},
     new Order() {Total = 647.518},
     new Order() {Total = 368.180},
     new Order() {Total = 12.84},
     new Order() {Total = 947.25},
};
 
if (orders.Any())
{
    //do something
}
 
if (orders.Count > 0)
{
    //do something
}

Both achieve the very same thing the second override is really useful it allows you to test all the items in the Enumeration for at least one match condition.

 
if (orders.Any(order => order.Total > 900))
{
    //do something
}

I am really struggling to come up with a good real world example of how/when to use Any so I wont at this time. But if you find yourself writing this code below, dont!

bool result = false;
foreach(var order in orders)
{
    if (order.Total > 900)
    { 
        result = true;
        break;
    }
}
 
if (result)
{
    //do something
}

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


Leave a Reply