👉🏼 Click here to Join I ❤️ .NET WhatsApp Channel to get 🔔 notified about new articles and other updates.
Using LINQ Any to Find Type of Data

Using LINQ Any to Find Type of Data

Author - Abdul Rahman (Bhai)

LINQ

26 Articles

Improve

Table of Contents

  1. What we gonna do?
  2. Why we gonna do?
  3. How we gonna do?
  4. Summary

What we gonna do?

In this article, let's learn about how to use Any in LINQ in .NET.

Note: If you have not done so already, I recommend you read the article on Using LINQ All to Find Type of Data.

We can determine the type of data contained within the collection using LINQ Any() method. The idea here is to find out if any items in a collection meet a specific condition. For primitive data types like int, decimal, string, etc we can just compare the values against other value in the collection.

Why we gonna do?

Any() solves the need to check whether at least one element in a collection satisfies a condition. Unlike a full loop, it short-circuits at the first match, making it efficient. It is useful for questions like: are there any students who passed? any orders that shipped? any customers who opted in? Without it, you'd need a loop that scans the entire collection even after finding the first match.

How we gonna do?

Common uses of Any method

LINQ Any() is used to answer questions about collection such as, any students passed the exam?, Do any orders got shipped? Do any customers opted for newsletters?. Let's take a look at syntax. The syntax for Any() is we apply the Any() method to some IEnumerable<T> collection and we specify a predicate. This is then going to check if any items within the collection match the given condition. For example, IEnumerable<T>.Any(predicate). This will return a boolean value true or false indicating do any element in the collection met the criteria?. The boolean result will be returned as soon as first match is found. This will not scan the entire collection.


List<Product> products = GetProducts();

//Method Syntax
bool result = products
              .Any(product => product.Size == 58);
                    
//Query Syntax
bool result = (from product in products select product)
              .Any(product => product.Size == 58);
            
Demo Space

Summary

In this article we learn't how to find type of data contained within collection using Any. This can be used to find if any items within collection matches a criteria or not. All these can be used with any IEnumerable or IQueryable types.

👉🏼 Click here to Join I ❤️ .NET WhatsApp Channel to get 🔔 notified about new articles and other updates.
  • LINQ
  • Any