
Using LINQ All to Find Type of Data
Author - Abdul Rahman (Bhai)
LINQ
26 Articles
Table of Contents
What we gonna do?
In this article, let's learn about how to use All in LINQ in .NET.
Note: If you have not done so already, I recommend you read the article on Using LINQ Chunk to Split Data.
We can determine the type of data contained within the collection using LINQ All() method. The idea here is to find out if all 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?
All() is useful when you need to verify that every element in a collection meets a specific condition. Without it, you'd write a loop with a boolean flag and check every element manually. All() returns false at the first non-match for efficiency, making it ideal for questions like: do all students pass? do all orders ship? do all customers opt in?
How we gonna do?
Common uses of All method
LINQ All() is used to answer questions about collection such as, all students passed the exam?, Do all orders got shipped? Do all customers opted for newsletters?. Let's take a look at syntax. The syntax for All() is we apply the All() method to some IEnumerable<T> collection and we specify a predicate. This is then going to check if all items within the collection match the given condition. For example, IEnumerable<T>.All(predicate). This will return a boolean value true or false indicating do all elements in the collection met the criteria?. The boolean result will be returned only after checking all elements in the collection. Hence this will scan the entire collection.
List<Product> products = GetProducts();
//Method Syntax
bool result = products
.All(product => product.Size == 58);
//Query Syntax
bool result = (from product in products select product)
.All(product => product.Size == 58);
Summary
In this article we learn't how to find type of data contained within collection using All. This can be used to find if all items within collection matches a criteria or not. All these can be used with any IEnumerable or IQueryable types.