Using LINQ Any to Find Type of Data
linq
26 Articles
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.
Table of Contents
Introduction
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.
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.
Code Sample - LINQ Any
Demo - LINQ Any Clause Demo
Let's try LINQ Any
- We have
Product
class with following properties -Id, Name, Color, Price, Size
- Enter the predicate to find if any product matches the condition.
- Click on Any Button
- Click on reset to try other combination
Id | Name | Color | Price | Size |
---|---|---|---|---|
1 | Shirt | Black | 1000 | 18 |
2 | Shirt | Red | 1500 | 28 |
3 | Shirt | Black | 2000 | 38 |
4 | Shirt | Red | 2500 | 48 |
5 | Shirt | Brown | 3000 | 58 |
6 | Shirt | White | 3500 | 68 |
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.